// var token = 'c4ca4238a0b923820dcc509a6f75849b';
var token = localStorage.getItem('token');

var varFilename = decodeURIComponent(decodeURIComponent(GetQueryString('file')));
var varTitle = decodeURIComponent(decodeURIComponent(GetQueryString('title')));

varFilename = !!varFilename ? varFilename : '';
varTitle = !!varTitle ? varTitle : '';

var time3,resocket,reajax,ws

// 各种单位
var calVars = {
    sex: 0,
    signSex: 0,
    // 普通单单位时间
    normalTimeUnit: 0,
    // 普通单基础时长
    normalTime: 0,
    // 加急单时长
    quickTime: 0,
    // 加急单单位时间
    quickTimeUnit: 0,
    // 加单单加价
    quickPricePercent: 0,
    // 预约单时长
    preTime: 0,
    // 预约单单位时间
    preTimeUnit: 0,
    // 预约单折扣
    prePriceDiscount: 0,
    // 配音单价
    priceUnit: {
        // 顶级主播单价
        5: 0,
        // 知名主播单价
        6: 0,
        // 优质主播单价
        7: 0
    },
    oid: 0,
};


// 设置个人信息项
personInfo.init(function() {
    // 更新dom callback
}, function(data) {
    // ajax调用后callback
    var data = data.data;
    countTime = data.qiangdanshixian * 2
    // 设置邮箱
    $('.mask_footer_e span').text(data.email);
    $('.sign_e span').text(data.email)
    $('#mask_email').get(0).value = data.email;
    $('.sign_email').get(0).value = data.email;
    //剩余字数
    $('.remainWord span strong').text(data.wordnumber)
    // 设置不同主播价格
    $('.footer_auther_lis').eq(0).find('p.px12.colff4330.left').text(data.levelC + '元 / 100字');
    $('.footer_auther_lis').eq(1).find('p.px12.colff4330.left').text(data.levelB + '元 / 100字');
    $('.footer_auther_lis').eq(2).find('p.px12.colff4330.left').text(data.levelA + '元 / 100字');
    // 设置用户账户价格
    $('.mask_footer_balance').text('￥' + data.balance);
    // 设置各种参数
    calVars = {
        signSex: data.signsex,
        sex: data.sex,
        // 普通单单位时间
        normalTimeUnit: data.putongdanshichang,
        // 普通单基础时长
        normalTime: data.putongdanjiashi,
        // 加急单时长
        quickTime: data.jiajidanjiashi,
        // 加急单单位时间
        quickTimeUnit: data.jiajidanshichang,
        // 加急单加价
        quickDiscount: data.jiajidanjiajia,
        // 预约单时长
        preTime: data.yuyuedanjiashi,
        // 预约单单位时间
        preTimeUnit: data.yuyuedanshichang,
        // 预约单折扣
        preDiscount: data.yuyuedanzhekou,
        //签约配音
        sigAnchor: parseFloat(data.pricing),
        // 配音单价
        priceUnit: {
            // 顶级主播单价
            5: data.levelA,
            // 知名主播单价
            6: data.levelB,
            // 优质主播单价
            7: data.levelC
        },
        balance: data.balance,
        //签约到期事件
        expire: data.deadline,
        //剩余字数
        words: data.wordnumber,
        //最晚下单事件
        lastTime: data.qianyuedanshixian
    };
    // 设置配音偏好
    $('.gender_wrapper input[type="radio"][value="' + data.sex + '"]').trigger('click');
    $('.speed_wrapper input[type="radio"][value="' + data.speed + '"]').trigger('click');
    $('#broadcast-type-select .option[data-value="' + data.soundtype + '"]').trigger('click');

    $('a.gotourl').on('click', function(ev) {

        var data = orderFunc.getAllData();
        if (data.title != '' || data.article != '') {
            ev.preventDefault();
            var $this = $(this);
            var url = $this.attr('href');

            commonConfirmBox.show({
                title: '退出文稿编辑',
                text: '退出文稿编辑将清空已输入内容'
            }, function() {
                $this.addClass('active');
            }, function() {
                window.location.href = url;
            }, function() {
                $this.removeClass('active');
            })
        }
        if (!$('#selShowHide').hasClass('hide')) {
            ev.preventDefault();
            var $this = $(this);
            var url = $this.attr('href');
            commonConfirmBox.show({
                title: '退出文稿编辑',
                text: '退出文稿编辑将清空已输入内容'
            }, function() {
                $this.addClass('active');
            }, function() {
                window.location.href = url;
            }, function() {
                $this.removeClass('active');
            })
        }
    });
    /*** 获取文章内容 begin */
    if (varFilename) {
        $('#document-title').val(varTitle);
        $.get(apiCollect.apiGetDocContent, {
            object: varFilename
        }, function(data) {
            if ('000000' == data.code) {
                $('.text-wrapper').html(data.data);
                orderFunc.updateHTML();
            } else {
                headtipObj.show(data.message);
            }
        })
    }
    // 根据 订单类型 判断修改页面
    var urlDemand = GetQueryString('demand') ? GetQueryString('demand') : 1;
    $('.service_h_option .service_option[data-type="' + urlDemand + '"]').trigger('click');

    if (urlDemand == 1) {
        // $('.mode-text').text('极速')
    } else if (urlDemand == 3) {
        $('.mode-text').text('预约')
    } else if (urlDemand == 4) {
        $('.mode-text').text('签约')
    }
});
/*** 获取文章内容 end */

$('body').click(function(e) {
    $('.footer_auther_li').hide();
    $('.service_h_option').hide();
    $('#broadcast-type-select').addClass('hide');
});
$('.footer_auther').click(function(e) {
    e.stopPropagation();
    var $list = $('.footer_auther_li');
    if ($list.css('display') == 'none') {
        $list.show();
    } else {
        $list.hide();
    }
});
$.each($('.footer_auther_lis'), function(index, item) {
    $(item).click(function(e) {
        e.stopPropagation();
        var html = $('.zhubo').eq(index).html();
        var lv = $('.footer_auther_lis .footer_li_name').eq(index).data('lv');
        $('.footer_li_name ').removeClass('footer_yes');
        $('.footer_li_name ').eq(index).addClass('footer_yes');
        $('.footer_auther_li').hide();
        $('#footer_auther_check').html(html).attr('data-lv', lv);
        orderFunc.updateHTML();
    })
});
//左上
$('.service_h_quick').click(function(e) {
    e.stopPropagation();
    var $pop = $('.service_h_option');
    // $('.service_h_option').show();
    if ($pop.css('display') == 'none') {
        $pop.show();
    } else {
        $pop.hide();
    }
});

// 配音类型
var TypeData
$('.service_h_option .service_option').click(function(ev) {
    ev.stopPropagation();
    var $this = $(this);
    var $quick = $('#quick');
    var html = $this.find('span').html();
    var value = $this.data('type');

    var $label = $(".gender_wrapper>label");
    var $disabled = $('#disabled');
    var $vip = $('.mask_footer_type.vip');
    var navListData = $this.data('mod');
    var $voice = $('#voice');
    orderFunc.updateHTML();
    if (!$this.hasClass('disabled')) {
        $('.service_h_option').hide();
        $voice.html(html).attr('data-type', value);
        $voice.html(navListData).attr('data-type', value);
        TypeData  = $('#voice').attr('data-type')
        console.log('配音类型切换', $voice.attr('data-type'));
        $('#right-nav .service_option').eq($(this).index()).css('background', '#e5e5e5').siblings().css('background', 'transparent')
        if (value == 3) {
            payProcess.payType = 1;
            console.log('当前支付方式为' + payProcess.payType);
            $quick.addClass('none');
            $('.tip-info').addClass('hide')
            $('#collect_wrap').hide();
            $quick.show();
            $('.footer_time_num_wrapper').show();
            $('.footer_auther').show();
            $('#custom-time').removeClass('none');
            timeSelector.resetValue();
        } else if (value == 1) {
            payProcess.payType = 1;
            console.log('当前支付方式为' + payProcess.payType);
            $quick.removeClass('none');
            $('.footer_btns .tip-info').addClass('hide');
            $('#collect_wrap').hide();
            $quick.show();
            $('.footer_time_num_wrapper').show();
            $('.footer_auther').show();
            $('#custom-time').addClass('none');
        }
        if (value == 4) {
            pay.removeClass('mask_bor_bg');
            payProcess.payType = 0;
            console.log('当前支付方式为' + payProcess.payType);
            $('.footer_time_num_wrapper').hide();
            $('.footer_btns .tip-info').addClass('hide');
            $('#quick').hide();
            $('.footer_auther').hide();
            $('#collect_wrap').show();
            $('#custom-time').addClass('none');
            $label.eq(calVars.signSex).siblings().children('input').prop('checked', false);
            $("input[name='gender']").eq(calVars.signSex).prop('checked', true);
            $label.eq(calVars.signSex).siblings().children('input').prop('disabled', true);
            $label.eq(calVars.signSex).siblings().click(function() {
                headtipObj2.show('还未开放该性别主播')
            });
            $('.footer_time_d').text('按约定时间交付');
            $('#collect_wrap').click(function() {
                headtipObj2.show('签约订单将派送给您指定的主播');
            });
            $vip.css({
                'border': '1px #659ce9 solid',
                'color': '#659ce9'
            });
            $('.mask_bor_bg:eq(0)').css({
                'border': '1px solid #e5e5e5',
                'color': '#e5e5e5'
            });
            $vip.unbind('click');
            payProcess.bindOrdinarySelect();
            if (calVars.balance) {
                $disabled.prop('disabled', false);
                $disabled.prop('checked', true);
            } else {
                $disabled.prop('checked', false);
                $disabled.prop('disabled', true);
            }
            $('#floatN').hide();
            $('.footer_time_d').css('margin-left', '-4px');
            $('#lastTime').removeClass('none');
            $('#expire').removeClass('none');
            $('.footer_rmb_right').css('background', '#5a8eb5').text('立即派单');
            $('.footer_rmb').css({
                'border': '1px #5a8eb5 solid',
                'color': '#5a8eb5'
            });
            // var c = b.replace(/\//g,'-','');
            $('#expire span').text('合约到期：' + calVars.expire);
            $('.tip-info').removeClass('hide').text('剩余字数').css('color', '#5a8eb5');
            $('#lastTime').text('(最晚下单后 ' + calVars.lastTime + ' 小时内)')


        } else {
            pay.eq(0).addClass('mask_bor_bg');
            $("input[name='gender']").prop('disabled', false);
            $label.eq(calVars.signSex).siblings().unbind('click');
            $('.gender_wrapper input[type="radio"][value="' + calVars.sex + '"]').prop('checked', true);
            $('.mask_footer_type.vip').css({
                'border': '1px #e5e5e5 solid',
                'color': '#e5e5e5'
            });
            $('.mask_bor_bg:eq(0)').css({
                'border': '1px solid #659ce9',
                'color': '#659ce9'
            });
            $('.mask_bor_bg:eq(0)').unbind('click');
            payProcess.bindVIPSelect();
            $disabled.prop('disabled', false);
            $disabled.prop('checked', true);
            $('#floatN').show();
            $('.footer_time_d').css('margin-left', '15px');
            $('#lastTime').addClass('none');
            $('#expire').addClass('none');
            $('.footer_rmb_right').css('background', '#ff2610').text('立即下单');
            $('.footer_rmb').css({
                'border': '1px #ff2610 solid',
                'color': '#ff2610'
            })
        }
        orderFunc.updateHTML();
    } else {
        headtipObj2.show('功能即将推出敬请期待')
    }
});
$('#right-nav .service_option').click(function(ev) {
    ev.stopPropagation();
    var $this = $(this);
    var $quick = $('#quick');
    var html = $this.find('span').html();
    var value = $this.data('type');
    var $label = $(".gender_wrapper>label");
    var $disabled = $('#disabled');
    var $vip = $('.mask_footer_type.vip');
    var navListData = $this.data('mod');
    var $voice = $('#voice');
    orderFunc.updateHTML();
    if (!$this.hasClass('disabled')) {
        $('.service_h_option').hide();
        $voice.html(html).attr('data-type', value);
        $voice.html(navListData).attr('data-type', value);
        console.log('配音类型切换', $voice.attr('data-type'));
        $(this).css('background', '#e5e5e5').siblings().css('background', 'transparent');
        if (value == 3) {
            payProcess.payType = 1;
            console.log('当前支付方式为' + payProcess.payType);
            $('.mode-text').text('预约')
            $quick.addClass('none');
             $('.tip-info').addClass('hide')
            // $('.tip-info').removeClass('hide').text('预约优惠20%').css('color', '#ff2610');
            $('#collect_wrap').hide();
            $quick.show();
            $('.footer_time_num_wrapper').show();
            $('.footer_auther').show();
            $('#custom-time').removeClass('none');
            headtipObj2.show('当前切换到预约配音');
            timeSelector.resetValue();
        } else if (value == 1) {
            payProcess.payType = 1;
            console.log('当前支付方式为' + payProcess.payType);
            $('.mode-text').text('极速')
            $quick.removeClass('none');
            $('.footer_btns .tip-info').addClass('hide');
            $('#collect_wrap').hide();
            $quick.show();
            $('.footer_time_num_wrapper').show();
            $('.footer_auther').show();
            $('#custom-time').addClass('none');
            headtipObj2.show('当前切换到极速配音')
        }
        if (value == 4) {
            pay.removeClass('mask_bor_bg');
            $('#sign_close').show()
            $('.sign_frist').addClass('col585858')
            payProcess.payType = 0;
            $('.mode-text').text('签约')
            console.log('当前支付方式为' + payProcess.payType);
            $('.footer_time_num_wrapper').hide();
            $('.footer_btns .tip-info').addClass('hide');
            $('#quick').hide();
            $('.footer_auther').hide();
            $('#collect_wrap').show();
            $('#custom-time').addClass('none');
            headtipObj2.show('当前切换到签约配音');
            $label.eq(calVars.signSex).siblings().children('input').prop('checked', false);
            $("input[name='gender']").eq(calVars.signSex).prop('checked', true);
            $label.eq(calVars.signSex).siblings().children('input').prop('disabled', true);
            $label.eq(calVars.signSex).siblings().click(function() {
                headtipObj2.show('还未开放该性别主播')
            });
            $('.footer_time_d').text('按约定时间交付');
            $('#collect_wrap').click(function() {
                headtipObj2.show('签约订单将派送给您指定的主播');
            });
            $vip.css({
                'border': '1px #659ce9 solid',
                'color': '#659ce9'
            });
            $('.mask_bor_bg:eq(0)').css({
                'border': '1px solid #e5e5e5',
                'color': '#e5e5e5'
            });
            $vip.unbind('click');
            payProcess.bindOrdinarySelect();
            if (calVars.balance) {
                $disabled.prop('disabled', false);
                $disabled.prop('checked', true);
            } else {
                $disabled.prop('checked', false);
                $disabled.prop('disabled', true);
            }
            $('#floatN').hide();
            $('.footer_time_d').css('margin-left', '-4px');
            $('#lastTime').removeClass('none');
            $('#expire').removeClass('none');
            $('.footer_rmb_right').css('background', '#5a8eb5').text('立即派单');
            $('.footer_rmb').css({
                'border': '1px #5a8eb5 solid',
                'color': '#5a8eb5'
            });
            // var c = b.replace(/\//g,'-','');
            $('#expire span').text('合约到期：' + calVars.expire);
            $('.tip-info').removeClass('hide').text('剩余字数').css('color', '#5a8eb5');
            $('#lastTime').text('(最晚下单后 ' + calVars.lastTime + ' 小时内)')
        } else {
            pay.eq(0).addClass('mask_bor_bg');
            $("input[name='gender']").prop('disabled', false);
            $label.eq(calVars.signSex).siblings().unbind('click');
            $('.gender_wrapper input[type="radio"][value="' + calVars.sex + '"]').prop('checked', true);
            $('.mask_footer_type.vip').css({
                'border': '1px #e5e5e5 solid',
                'color': '#e5e5e5'
            });
            $('.mask_bor_bg:eq(0)').css({
                'border': '1px solid #659ce9',
                'color': '#659ce9'
            });
            $('.mask_bor_bg:eq(0)').unbind('click');
            payProcess.bindVIPSelect();
            $disabled.prop('disabled', false);
            $disabled.prop('checked', false);
            $('#floatN').show();
            $('.footer_time_d').css('margin-left', '15px');
            $('#lastTime').addClass('none');
            $('#expire').addClass('none');
            $('.footer_rmb_right').css('background', '#ff2610').text('立即下单');
            $('.footer_rmb').css({
                'border': '1px #ff2610 solid',
                'color': '#ff2610'
            })
        }
        orderFunc.updateHTML();
    } else {
        headtipObj2.show('功能即将推出敬请期待')
    }
});
$('.service_h_option .service_option').on('mouseover', function(ev) {
    ev.stopPropagation();
    var $this = $(this);
    if ($this.hasClass('disabled')) {
        $('.service_h_option .service_h_talk').show().css('top', $this[0].offsetTop)
    } else {
        $('.service_h_option .service_h_talk').hide();
    }
});
$('.service_h_option .service_option,#right-nav .service_option').on('mouseleave', function() {
    $('.service_h_talk').hide()
});
$('#right-nav .service_option').on('mouseover', function(ev) {
    ev.stopPropagation();
    var $this = $(this);
    if ($this.index() == 0) {
        $('#right-nav .service_h_talk').text('极速配音').show().css('top', $this[0].offsetTop + 3)
    } else if ($this.index() == 1) {
        $('#right-nav .service_h_talk').text('预约配音').show().css('top', $this[0].offsetTop + 3)
    } else if ($this.index() == 2) {
        $('#right-nav .service_h_talk').text('签约配音').show().css('top', $this[0].offsetTop + 3)
    } else {
        $('#right-nav .service_h_talk').text('即将上线').show().css('top', $this[0].offsetTop + 3)
    }
});
// 播报类型选择
$('#broacast-type').click(function(e) {
    e.stopPropagation();
    $pop = $('#broadcast-type-select');
    if ($pop.css('display') == 'none') {
        $pop.removeClass('hide');
    } else {
        $pop.addClass('hide');
    }
});

// 加急按钮
$('input.footer_checked').on('change', function() {
    orderFunc.updateHTML();
});
//支付弹框
var rmb = $('.footer_rmb_right');
var mask = document.getElementById('mask_speed');
var signTem = document.getElementById('signTemplate');
var close = document.getElementById('mask_close');
var signClose = document.getElementById('sign_close');
// close = $('.mask_close');
one = $('#mask_speed .mask_pay_one');
two = $('#mask_speed .mask_pay_two');
three = $('#mask_speed .mask_pay_three');
lis = $('.mask_footer_type');
mailbox = $('.mailbox');
modify = $('.modify');
btn = $('.mask_btn');
pay = $('.mask_footer_pay');

signTem.onclick = function(ev) {
    payProcess.signClose();
};
close.onclick = function() {
    payProcess.close();

};
signClose.onclick = function() {
    payProcess.signClose();
};
if (mask.find) {
    mask.find('.mask_speed_cont').click(function(ev) {
        ev.stopPropagation();
    });
} else {
    mask.getElementsByClassName('mask_speed_cont')[0].onclick = function(event) {
        event.stopPropagation();
    }
}
if (signTem.find) {
    signTem.find('.mask_speed_cont').click(function(ev) {
        ev.stopPropagation();
    });
} else {
    signTem.getElementsByClassName('mask_speed_cont')[0].onclick = function(event) {
        event.stopPropagation();
    }
}
$('#allWrap').hide();
$('#allWrap').click(function() {
    $('#fiveContent').addClass('hide');
    $('#allWrap').hide()
});

// 默认自选主播未开启
var totalPrice = 0,basicPrice = 0,urgentPrice = 0,originPrice = 0,bgMusicPrice = 0,subscribePrice = 0
var ischose = 0
var flag = true
var timer2
$('.ischose').hide()
$('.noti-config-switch.sm-switch').click(function() {
    $('#optional-select').hide()
    if (flag == true && ischose == 0) {
        ischose = 1
        flag = false
        $('.groove').css({
            'background': 'linear-gradient(180deg,#eb402a,#eb402c)',
            'border-color': '#eb402a',

            'box-shadow': 'inset 0 1px 3px #af210e',

        })
        $('.stick').css({'left': '25px',});
        $('.ischose').show()
        // 自选增价
        originPrice = basicPrice * 0.2
        // 总价
        totalPrice = basicPrice * 1.2
        // 预约单总价
        if( $('#voice').attr('data-type') == 3){
            totalPrice = basicPrice * 0.8 + originPrice
        }
        // 背景音增价
        if (!$('#selShowHide').hasClass('hide')) {
            totalPrice += 20
        }else{
            bgMusicPrice = 0
        }
        // 加急增价
        if(orderFunc.getQuickBool() == 1){
            totalPrice += urgentPrice
        }
        console.log(ischose)
    } else if(flag != true || ischose != 0){
        ischose = 0
        totalPrice -= originPrice
        flag = true
        $('.groove').css({
            'background': '#eee',
            'border-color': '#ddd',
            'box-shadow': 'inset 0 2px 3px #ccc'
        })
        $('.stick').css({
            'left': '0',
        });
        $('.ischose').hide()
        originPrice = 0
          console.log(ischose)
    }

    var textLen = orderFunc.getInputTextLength()
    if(orderFunc.getInputTextLength() != 0){
        $('.footer_rmb').html('￥ '+totalPrice.toFixed(2) + '<span>＞</span>')
        if(orderFunc.getVolType != 4 ){
           $('.footer_rmb').hover(function() {
                // 总价
                // $('.footer_rmb').text("￥ " + totalPrice.toFixed(2))
                $('.total-price').text(totalPrice.toFixed(2))
                $('.basic-price').text(basicPrice.toFixed(2))
                $('.urgent-price').text(urgentPrice.toFixed(2))
                $('.origin-price').text(originPrice.toFixed(2))
                $('.bg-music-price').text(bgMusicPrice.toFixed(2))
                // 预约
                $('.subscribe-price').text(subscribePrice.toFixed(2))
                if(finalType == 4){
                    console.log(finalType)
                     $('.total-info').hide()
                }else{
                     $('.total-info').show()
                }
            }, function() {
                $('.total-info').hide()
            })
        }else{
            $('.total-info').hide()
        }

    }else{
         $('.footer_rmb').html('￥ '+ 0 + '<span>＞</span>')
    }
});

// 立即下单
rmb.click(function() {
    // 显示弹层
    var data = orderFunc.getAllData();
    var text = $('.text-wrapper').text();
    if ($('#voice').text() == '签约配音') {
        $('#fiveContent').addClass('hide');
        if (!data.title) {
            headtipObj.show('标题不能为空');
        } else if (!data.article) {
            headtipObj.show('内容不能为空');
        } else if (data.title.length < 5) {
            headtipObj.show('标题不能少于5个字');
        } else {
            payProcess.signShow(data);
        }
    } else {
        if (!data.title) {
            headtipObj.show('标题不能为空');
        } else if (!data.article) {
            headtipObj.show('内容不能为空');
        } else if (data.title.length < 5) {
            headtipObj.show('标题不能少于5个字');
        } else if ($('.footer_word_num').text() < 500) {
            $('#fiveContent').removeClass('hide');
            $('#allWrap').show()
        } else {
            payProcess.show(data);
        }
    }
});
$('#sub').click(function(e) {
    e.stopPropagation();
    var data = orderFunc.getAllData();
    $('#allWrap').hide();
    payProcess.show(data);
    $('#fiveContent').addClass('hide')
});

var anchorListStr = ''
var SelectFlag = false
var miss
var payProcess = {
    payType: 0,
    oid: GetQueryString("oid"),
    token: '',
    ajaxLock: false,
    readtitle: 1,
    api: {
        // createOrder: 'http://testmedia.heardtech.com/Post/CreateOrder', // 新建订单
        // getQR: 'http://testmedia.heardtech.com/Post/PayOrder',                   // 获取二维码
        // getPayResult: 'http://testmedia.heardtech.com/Post/ajaxOrderIspay',  // 获取付款结果
        createSignOrder: apiCollect.apiCreateSignOrder, //创建签约订单
        createOrder: apiCollect.apiCreateOrder, // 新建订单
        getQR: apiCollect.apiGetWXQR, // 获取二维码
        getPayResult: apiCollect.apiGetPayStatus // 获取付款结果
    },
    balance: 0,
    intervalID: '',
    regEmail: /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/,
    // 倒计时结束
    num_cunout: 0,
    anchor_type: 1,
    //随机步长
    step: 0,
    anchor_num: 0,
    // anchor_list: {},
    // 倒计时结束
    num_cunout: 1,
    anchor_type: 0,
    addCount: 0,
    uuid: '',

    init: function(token) {
        var _this = this;
        _this.setToken(token);
        // 绑定下一步
        $('.mask_btn').on('click', function() {
            var type = $('#voice').attr('data-type');

            // 是否使用余额支付
            console.log(type)
            // 4.19 两种订单区分
            if (type == 4) {
                _this.createSignOrder()
            } else {
                _this.getQR();
            }
        });
        $('.sign_btn').click(function() {
            _this.createSignOrder()
        });
        this.bindEditEmail();
        this.bindSignEditEmail();
        this.bindUseBalance();
        this.bindVIPSelect();
        this.bindOrdinarySelect();
        this.tabPayType();
        this.tabReadTitle();
    },
    bindOrdinarySelect: function() {
        $('.mask_bor_bg').get(0).click(function() {
            headtipObj2.show('签约订单仅对高级用户开放');
        })
    },
    bindVIPSelect: function() {
        $('.mask_footer_type.vip').click(function() {
            headtipObj2.show('该功能仅对高级版/企业版充值用户开放');
        })
    },
    bindAlipay: function() {
        $('.mask_footer_pay.alipay').click(function() {
            headtipObj2.show('支付宝维护中 请稍后再试');
        })
    },
    tabPayType: function() {
        pay.click(function() {
            var $this = $(this);
            $this.addClass('mask_bor_bg').siblings().removeClass('mask_bor_bg');
            var $alipay = $('.alipay');
            var $list = $('.mask_pay_list');
            $('.mask_total_m .total-container > span').text('总计：');
            $('#mask_money_count').text('￥' + totalPrice.toFixed(2));
            $('#disabled').prop("checked", false);
            if (!$alipay.hasClass('mask_bor_bg')) {
                $list.children('img').attr('src', 'img/public/pay_13.png');
                $list.children('span').text('请用微信扫码完成支付');
                payProcess.payType = 1;
                console.log('当前支付模式:' + payProcess.payType)

            } else if ($alipay.hasClass('mask_bor_bg')) {
                $list.children('img').attr('src', 'img/public/pay_14.png');
                $list.children('span').text('请用支付宝扫码完成支付');
                payProcess.payType = 2;
                console.log('当前支付模式:' + payProcess.payType)
            }
        })
    },
    //切换朗读
    tabReadTitle: function() {
        var _this = this;
        var noTalk = 'img/noTalk.png';
        var talk = 'img/talk.png';
        var mouseoverNoTalk = 'img/mouseoverNoTalk.png';
        var mouseoverTalk = 'img/mouseoverTalk.png';
        var mouseDownTalk = 'img/mouseDownTalk.png';
        var mouseDownNoTalk = 'img/mouseDownNoTalk.png';
        $('#document-wrapper>.header>div').on({
            mouseover: function() {
                if ($(this).hasClass('on')) {
                    $(this).children('img').attr('src', mouseoverTalk)
                } else {
                    $(this).children('img').attr('src', mouseoverNoTalk)
                }
            },
            mouseout: function() {
                if ($(this).hasClass('on')) {
                    $(this).children('img').attr('src', talk)
                } else {
                    $(this).children('img').attr('src', noTalk)
                }
            },
            mousedown: function() {
                if ($(this).hasClass('on')) {
                    $(this).children('img').attr('src', mouseDownTalk)
                } else {
                    $(this).children('img').attr('src', mouseDownNoTalk)
                }
            },
            mouseup: function() {
                if ($(this).hasClass('on')) {
                    $(this).removeClass('on');
                    _this.readtitle = 0;
                    $(this).children('p').text('标题无需朗读');
                    $(this).children('img').attr('src', noTalk)
                } else {
                    $(this).addClass('on');
                    _this.readtitle = 1;
                    $(this).children('p').text('标题必须朗读');
                    $(this).children('img').attr('src', talk)
                }
            }
        })
    },
    bindEditEmail: function() {
        $('.mask_footer_e .modify').click(function() {
            var $this = $(this);
            var $container = $('.mask_footer_e');
            if ($container.hasClass('active')) {
                $this.text('修改');
                $container.removeClass('active');
                $('#mask_email').addClass('hide');
                $('.mask_footer_e span').show().text($('#mask_email').val());
            } else {
                $this.text('确认');
                $container.addClass('active');
                $('.mask_footer_e span').hide();
                $('#mask_email').removeClass('hide');
            }
        })
    },
    bindSignEditEmail: function() {
        $('.sign_e .modify').click(function() {
            var $this = $(this);
            var $container = $('.sign_e');
            if ($container.hasClass('active')) {
                $this.text('修改');
                $container.removeClass('active');
                $('.sign_email').addClass('hide');
                $('.sign_e span').show().text($('.sign_email').val());
            } else {
                $this.text('确认');
                $container.addClass('active');
                $('.sign_e span').hide();
                $('.sign_email').removeClass('hide');
            }
        })
    },
    bindUseBalance: function() {
        var _this = this;
        $('.mask_footer_b .checkbox-simulator').on('change', function(ev) {
            var $this = $(this);
            var useBool = $this.prop('checked');
            if (useBool) {
                if (_this.balance <= 0) {
                    $('#disabled').prop("checked", false);
                    headtipObj2.show('您的余额不足 请前往充值套餐');
                    _this.payType = payProcess.payType
                    pay.addclass('mask_bor_bg')
                }
                // 使用余额
                var realPrice = _this.balance - totalPrice >= 0 ? 0 : totalPrice - _this.balance;
                console.log(realPrice);
                $('.mask_total_m .total-container > span').text('实际支付：');
                $('#mask_money_count').text('￥' + realPrice.toFixed(2));
                pay.removeClass('mask_bor_bg')
            } else {
                $('.mask_total_m .total-container > span').text('总计：');
                console.log(totalPrice)
                $('#mask_money_count').text('￥' + totalPrice.toFixed(2));
                // $('#mask_money_count').text('￥' + realPrice.toFixed(2));
            }
        })
    },
    setOid: function(oid) {
        this.oid = oid;
    },
    setToken: function(token) {
        this.token = token;
    },
    show: function(allData) {
        var _this = this;
        $('#pay_back').hide()
        $('.frist').addClass('col585858')
        $.post(apiCollect.apiGetBalance, {
            wid: localStorage.getItem('wid')
        }, function(data) {
            if (data.code == '000000') {
                _this.balance = data.data.balance;
                $('#mask_speed .mask_footer_balance').text('￥' + data.data.balance);
                if (_this.balance <= 0) {
                    $('#disabled').prop("checked",false);
                } else {
                    $('#disabled').prop("checked",true);
                    var realPrice = _this.balance - orderFunc.price >= 0 ? 0 : orderFunc.price - _this.balance;
                    $('.mask_total_m .total-container > span').text('实际支付：');
                    $('#mask_money_count').text('￥' + realPrice.toFixed(2));
                    pay.removeClass('mask_bor_bg')
                }
                mask.style.display = 'block';
                $('#mask_speed .mask_cont_head span').text('支付订单');
                // 4.19 测试代码
                // 支付提交
                $('.mask_pay_one').show().siblings().hide()
                if(ischose == 0){
                     $('.mask_older_deep').css('margin-left','83px')
                }else{
                    $('.mask_older_deep').css('margin-left','42px')
                }
                _this.allData = allData;
            } else {
                headtipObj.show(data.message);
            }
        })
    },
    signShow: function(allData) {
        var _this = this
        var textLen = $('.footer_word_num').text();
        signTem.style.display = 'block';
        $('#signTemplate .mask_pay_one').show();
        $('#signTemplate .mask_pay_two').hide();
        $('#signTemplate .mask_pay_three').hide();
        $('.consumeWord strong').text(textLen + ' 字');
        _this.allData = allData;
        $('#pay_back').hide()
    },
    close: function() {
        clearInterval(resocket)
        clearInterval(reajax)
        mask.style.display = 'none';
        clearInterval(this.intervalID);
        $('.ischose').addClass('colacacac').removeClass('col585858')
        this.anchor_num = 0
        $('#notice-num').text('0')
        clearTimeout(miss)
        clearInterval(timer2)
        console.log(timer2)
        anchorListStr = ''
        // this.ajaxLock == false
        $('.info-tag').empty()
        $('.final').removeClass('col585858')

        $('#process-num').text('60s')
        $('#process-bar').hide().css({
            'width': '360px'
        })
        $('.select-anchor-btn').css({'background': "#333",'opacity': '1'}).val('确认下单')

    },
    signClose: function() {
        signTem.style.display = 'none';
    },
    //创建签约主播
    createSignOrder: function() {
        var _this = this;
        if (_this.ajaxLock) return; // 如果有锁 则不进行操作
        _this.ajaxLock = true; // 如果无锁 先锁定
        var dt = _this.allData;
        dt.email = $('.sign_email').get(0).value;
        if (!_this.regEmail.test(dt.email)) {
            headtipObj.show('邮箱格式不正确');
            _this.ajaxLock = false;
        } else if (!$('#signTemplate .checkbox-simulator').prop('checked')) {
            headtipObj.show('请选择字数余额支付');
            _this.ajaxLock = false;
        } else {
            $.ajax({
                type: "post",
                data: dt,
                async: false,
                url: _this.api.createSignOrder,
                success: function(data) {
                    if (data.code == '000000') {
                        _this.setOid(data.data.oid);
                        _this.oid = data.data.oid
                        $.post(apiCollect.apiPaySignOrder, {
                            token: _this.token,
                            oid: _this.oid,
                            email: dt.email
                        }, function(data) {
                            if (data.code == '000000') {
                                $('.mask_pay_three').show().siblings().hide()
                                $('#signTemplate .order_head').eq(0).removeClass('col585858').addClass('colacacac');
                                $('#signTemplate .order_head').eq(1).removeClass('col585858').addClass('colacacac');
                                $('#signTemplate .order_head').eq(2).removeClass('colacacac').addClass('col585858');
                            } else {
                                headtipObj.show(data.message);
                                _this.ajaxLock = false;
                            }
                            // 解锁
                            _this.ajaxLock = false;
                        })
                    } else {
                        headtipObj.show(data.message);
                        _this.ajaxLock = false;
                    }
                },
                error: function(data) {
                    $('#signTemplate').addClass('hide');
                    $('#signTemplate .mask_pay_one').hide();
                    headtipObj.show(data.message);
                    _this.ajaxLock = false;
                }
            });
        }
    },
    // 获取qr
    getQR: function() {
        var _this = this;
        if (_this.ajaxLock) return; // 如果有锁 则不进行操作
        _this.ajaxLock = true; // 如果无锁 先锁定
        var dt = _this.allData;
        dt.email = $('#mask_email').get(0).value;
        // dt.oid = _this.oid;
        if (!_this.regEmail.test(dt.email)) {
            headtipObj.show('邮箱格式不正确');
            _this.ajaxLock = false;
        } else if (!$('.mask_footer_pay').hasClass('mask_bor_bg') && !$('#disabled').prop('checked')) {
            headtipObj.show('请选择支付方式');
            _this.ajaxLock = false;
        } else {
            $.ajax({
                type: "post",
                data: dt,
                async: false,
                url: _this.api.createOrder,
                success: function(data) {
                    if (data.code == '000000') {
                        // $('#mask_money_count').text('￥' + data.data.money); // 更新弹窗价格
                        var paymoney = data.data.money;
                        // $('.mask_cont_head span').text('支付订单(￥' + parseFloat(paymoney) + ')');
                        _this.setOid(data.data.oid);
                        $.post(_this.api.getQR, {
                            token: _this.token,
                            oid: _this.oid,
                            email: dt.email,
                            paytype: payProcess.payType, // 1 微信 2 支付宝
                            isbalance: $('.mask_footer_b input[type="checkbox"]').prop('checked') ? 1 : 0
                        }, function(data) {
                            if (data.code == '000000') {
                                if (data.data.paystate == 1) {
                                    $('.order_head').eq(0).removeClass('col585858').addClass('colacacac');
                                    $('.order_head').eq(1).removeClass('col585858').addClass('colacacac');
                                    $('.order_head').eq(2).removeClass('colacacac').addClass('col585858');
                                    $('.final').addClass('col585858')
                                    if(ischose == 1){
                                        // 直接使用余额支付
                                        $('.being-notified').show().siblings().hide()
                                        $('.mask_close').hide()
                                        $('#pay_back').hide()
                                        // 随机数
                                        timer2 = setInterval(function() {
                                            _this.addCount++
                                            _this.step =  Math.floor(Math.random()*2 + 1),
                                            _this.anchor_num += _this.step
                                            $('#notice-num').text(_this.anchor_num)
                                        }, 3000)
                                        if(_this.anchor_num >= 125){
                                               $.ajax({
                                                    url: apiCollect.apiPostChoseOrder,
                                                    type: 'post',
                                                    dataType: 'json',
                                                    data: {
                                                        token: localStorage.getItem('token'),
                                                        oid: _this.oid,
                                                    },
                                                    success: function(data){
                                                        if(data.code = '000000'){
                                                           // 没主播
                                                            $('.no-one-accept').show().siblings().hide()
                                                            $('#mask_close').show()
                                                            $('.order_head').removeClass('col585858').addClass('colacacac')
                                                            $('.final').addClass('col585858')
                                                            $('.anchors-list-content').empty()
                                                            _this.anchor_num == 0
                                                        }
                                                    },
                                                    error: function(data){
                                                        console.log(data)
                                                    }

                                                })
                                        }
                                         $('.final').removeClass('col585858')
                                        _this.anchorNum()
                                     }else {
                                        $('.mask_pay_three').show().siblings().hide()
                                     }
                                    $('.mask_pay_three').find('.ishose0').show()
                                    $('.mask_pay_three').find('.ishose1').hide()

                                    $('.mask_speed .mask_cont_head span').text('支付订单')
                                } else if (data.data.paystate == 0) {
                                    // 继续支付
                                    // 修改价格
                                    $('.mask_pay_one').hide();
                                    $('.mask_pay_two').show();
                                    $('.mask_speed .mask_cont_head span').text('支付订单(￥' + paymoney + ')');
                                    $('#pay_back').show()
                                    $('.order_head').eq(0).removeClass('col585858').addClass('colacacac');
                                    $('.order_head').eq(1).removeClass('colacacac').addClass('col585858');
                                    $('#paycode img').attr('src', data.data.fileName);
                                    // 轮询 访问付款结果
                                    $('.mask_close').show()
                                    _this.getPayResultLoop();
                                }
                            } else {
                                Dialog.error(data.message);
                                _this.ajaxLock = false;
                            }
                            // 解锁
                            _this.ajaxLock = false;
                        })
                    }
                },
                error: function(data) {
                    mask.style.display = 'none';
                    one.hide();
                    headtipObj.show(data.message);
                    _this.ajaxLock = false;
                }
            });
        }
    },
    // 轮询 获取付款结果
    getPayResultLoop: function() {
        var _this = this;
        var cont = true;
        time3 = _this.intervalID = setInterval(function() {
            if (cont) {
                cont = false;
                // 询问
                $.post(_this.api.getPayResult, {
                    token: _this.token,
                    oid: _this.oid
                }, function(data) {
                    if (data.code == '000000') {
                        if (data.data.is_pay == 1) {
                            if(ischose == 1){
                                $('.mask_close').hide()
                                $('#pay_back').hide()
                                $('.being-notified').show().siblings().hide()
                                // 随机数
                                timer2 = setInterval(function() {
                                    _this.addCount++
                                    _this.step =  Math.floor(Math.random()*2 + 1),
                                    _this.anchor_num += _this.step
                                    $('#notice-num').text(_this.anchor_num)
                                }, 3000)
                                if(_this.anchor_num >= 125){
                                       $.ajax({
                                            url: apiCollect.apiPostChoseOrder,
                                            type: 'post',
                                            dataType: 'json',
                                            data: {
                                                token: localStorage.getItem('token'),
                                                oid: _this.oid,
                                            },
                                            success: function(data){
                                                if(data.code = '000000'){
                                                    // 没主播
                                                    $('.no-one-accept').show().siblings().hide()
                                                    $('#mask_close').show()
                                                    $('.order_head').removeClass('col585858').addClass('colacacac')
                                                    $('.final').addClass('col585858')
                                                    $('.anchors-list-content').empty()
                                                    _this.anchor_num == 0
                                                }
                                            },
                                            error: function(data){
                                                console.log(data)
                                            }

                                        })
                                }
                                // 连接socket
                                 $('.final').removeClass('col585858')
                                 _this.anchorNum()
                            }else{
                                console.log($('.mask_pay_three').find('.ischose0'))
                                $('.final').addClass('col585858')
                                $('.mask_pay_three').show().siblings().hide()
                                $('.mask_pay_three').find('.ishose0').show()
                                $('.mask_pay_three').find('.ishose1').hide()
                                $('.mask_close').show()
                            }
                            $('.order_head').eq(1).removeClass('col585858').addClass('colacacac');
                            $('.order_head').eq(2).removeClass('colacacac').addClass('col585858');
                            $('.mask_speed .mask_cont_head span').text('支付订单');
                            $('#pay_back').hide()
                            clearInterval(_this.intervalID);
                        } else {
                            // 失败
                            cont = true;
                            _this.ajaxLock = false;
                        }
                    } else {
                        Dialogdialog - mask.error(data.messge);
                        _this.ajaxLock = false;
                    }
                })
            }
        }, 1000);
    },

    // 随机通知主播个数
    anchorNum: function() {
        var _this = this
        if ("WebSocket" in window) {
            // 测试
            // ws = new WebSocket("ws://47.95.237.155:2345")
            ws = new WebSocket("ws://59.110.232.52:2345");
            ws.onopen = function() {
                ws.send(_this.oid)
            }
            ws.onmessage = function (evt) {
                //不parse你啥也看不明白
                var data = JSON.parse(evt.data).data.data
                var state = JSON.parse(evt.data).data.state
                if( state == '201'){
                    // 没主播
                    $('.mask_pay_three').find('.ishose1').hide()
                    $('.mask_pay_three').find('.ishose0').hide()
                    $('.no-one-accept').show().siblings().hide()
                    $('.no-one-accept .mask_finish').find('img').css({
                        'margin': '55px 134px 24px 124px',
                        'width': '130px'
                    });
                    $('#mask_close').show()
                    $('.order_head').removeClass('col585858').addClass('colacacac')
                    $('.final').addClass('col585858')
                    $('.anchors-list-content').empty()
                }else if(state == '202'){
                    // 未选择
                    $('.mask_pay_three').show().siblings().hide()
                    $('.mask_pay_three .ok_info').text('下单成功，已为你优选主播')
                    $('.mask_close').show()
                    // 优选
                     $('.mask_pay_three .mask_finish').find('img').css({
                        'margin': '40px 134px 24px 133px'
                    });
                   var selectData = JSON.parse(evt.data).data
                    $('#selectInfo-scorenum').text(selectData.scorenum)
                    if(selectData.sex == 1){
                        $('.info-sex').html('<img src="./img/optional/sex-man-img.png">')
                    }else if(selectData.sex == 2){
                        $('.info-sex').html('<img src="./img/optional/sex-woman-img.png">')
                    }
                    $('#info-username').text(selectData.nickname)
                    $('#info-ordertime').text(selectData.ordertime)
                    var label =selectData.label
                    for(i in label){
                        $('.info-tag').append("<span style='margin: 0 2px;'>" + label[i] + "</span>" )
                    }

                    $('.mask_pay_three').find('.ishose1').show()
                    $('.mask_pay_three').find('.ishose0').hide()

                    $('.order_head').removeClass('col585858').addClass('colacacac')
                    $('.final').addClass('col585858')
                    $('.order_head').eq(4).removeClass('col585858').addClass('colacacac');
                    $('.list-play-btn').empty()
                }else{
                    anchorListStr = ''

                    for( anchor_list in data){

                        // 渲染列表
                        anchorListStr += "<div class='anchors-list-detail' onclick='payProcess.test(this)'>"
                        anchorListStr += "<span class='list-play-btn' onclick='payProcess.playSound(this,"+ "&quot;" +  data[anchor_list].short_audio + "&quot;"
                        anchorListStr +=  ")'>"
                        anchorListStr +=  "<img src='./img/optional/play.png' />"
                        anchorListStr += "</span>"
                        anchorListStr += "<span class='list-user-info'><div>"
                        anchorListStr += "<span class='preferred'>优选</span>"
                        anchorListStr += "<span class='stars'>" + "<img src='./img/optional/stars.png'>"
                        anchorListStr += "<span>" + data[anchor_list].scorenum + "</span></span></div></span>"
                        anchorListStr += "<span class='sex'>"
                        if(data[anchor_list].sex == 1){
                            anchorListStr += "<span><img src='./img/optional/sex-man-img.png'></span></span>"
                        }else if(data[anchor_list].sex == 2){
                            anchorListStr += "<span><img src='./img/optional/sex-woman-img.png'></span></span>"
                        }
                        anchorListStr += "<span class='userInfo'  style='margin-left: 6px;'>"
                        anchorListStr += "<span id='username' style='margin-left: 0;'>" + data[anchor_list].nickname + "</span>"
                        anchorListStr += "<div id='ordertime'>服务" + "<span style='color: #ea3f2a'>" + data[anchor_list].ordertime
                        anchorListStr += "</span>次数</div></span>"

                        anchorListStr += "<span class='anchor-tag'>"
                        var label = data[anchor_list].label
                        for(i in label){
                            anchorListStr += "<span style='margin: 0 3px;'>" + label[i] + "</span>"
                        }
                        anchorListStr += "</span></span>"

                        var str = ''
                        str = data[anchor_list].uuid;
                        anchorListStr += "</span><span class='list-service-radio' style='margin-right:11px;' onclick='payProcess.selectAnchor(this,"+ "&quot;" + str + "&quot;" + ")'>"

                        if(_this.uuid == data[anchor_list].uuid){
                            anchorListStr += "<img class='select-btn' src='./img/optional/checked-btn.png'>"
                        }else{
                            anchorListStr += "<img class='select-btn' src='./img/optional/unchecked-btn.png'>"
                        }



                        anchorListStr += "<i style='display:none;'>"+ str + "</i>"
                        anchorListStr += "</span></div>"
                    }
                    if(anchor_list == 0){
                        miss = setTimeout(function(){
                            countDown(countTime,'process-bar')
                            $('#process-bar').show()
                        },120000)

                        $('.anchors-list-content').empty()
                        $('.anchors-list-content').append(anchorListStr)
                    }else{
                        console.log(anchorListStr)
                        console.log($('.select-btn').find('audio').length)
                        console.log(SelectFlag)
                       if($('.select-btn').find('audio').length == 0 && SelectFlag == false){
                            $('.anchors-list-content').empty()
                            $('.anchors-list-content').append(anchorListStr)
                            // SelectFlag = true
                        } else{
                            $('#anchorSound').bind('ended',function () {
                                $('.anchors-list-content').empty();
                                $('.anchors-list-content').append(anchorListStr)
                            });
                        }
                    }
                    var len = $('.anchors-list-detail').length
                    if(len > 3){
                        $('.anchors-list-content').css({
                            'overflow': 'scroll',
                            'overflow-x': 'hidden'
                        })
                    }
                    $('.mask_pay_select').show().siblings().hide()
                }
            }
        }
        _this.resocket()
        _this.reajax()
    },
    resocket: function(){
        var _this = this
        resocket = setInterval(function(){
            // ws = new WebSocket("ws://47.95.237.155:2345");
            ws = new WebSocket("ws://59.110.232.52:2345");
            ws.onopen = function() {
                ws.send(_this.oid)
            }
             ws.onmessage = function (evt) {
                //不parse你啥也看不明白
                var data = JSON.parse(evt.data).data.data
                var state = JSON.parse(evt.data).data.state
                if( state == '201'){
                    // 没主播
                    $('.mask_pay_three').find('.ishose1').hide()
                    $('.mask_pay_three').find('.ishose0').hide()
                    $('.no-one-accept').show().siblings().hide()
                    $('.no-one-accept .mask_finish').find('img').css({
                        'margin': '55px 134px 24px 124px',
                        'width': '130px'
                    });
                    $('#mask_close').show()
                    $('.order_head').removeClass('col585858').addClass('colacacac')
                    $('.final').addClass('col585858')
                    $('.anchors-list-content').empty()
                }else if(state == '202'){
                    // 未选择
                    $('.mask_pay_three').show().siblings().hide()
                    $('.mask_pay_three .ok_info').text('下单成功，已为你优选主播')
                    $('.mask_close').show()
                    // 优选
                     $('.mask_pay_three .mask_finish').find('img').css({
                        'margin': '40px 134px 24px 133px'
                    });
                   var selectData = JSON.parse(evt.data).data
                    $('#selectInfo-scorenum').text(selectData.scorenum)
                    if(selectData.sex == 1){
                        $('.info-sex').html('<img src="./img/optional/sex-man-img.png">')
                    }else if(selectData.sex == 2){
                        $('.info-sex').html('<img src="./img/optional/sex-woman-img.png">')
                    }
                    $('#info-username').text(selectData.nickname)
                    $('#info-ordertime').text(selectData.ordertime)
                    var label =selectData.label
                    for(i in label){
                        $('.info-tag').append("<span style='margin: 0 2px;'>" + label[i] + "</span>" )
                    }

                    $('.mask_pay_three').find('.ishose1').show()
                    $('.mask_pay_three').find('.ishose0').hide()

                    $('.order_head').removeClass('col585858').addClass('colacacac')
                    $('.final').addClass('col585858')
                    $('.order_head').eq(4).removeClass('col585858').addClass('colacacac');
                    $('.list-play-btn').empty()
                }else{
                    anchorListStr = ''

                    for( anchor_list in data){

                        // 渲染列表
                        anchorListStr += "<div class='anchors-list-detail' onclick='payProcess.test(this)'>"
                        anchorListStr += "<span class='list-play-btn' onclick='payProcess.playSound(this,"+ "&quot;" +  data[anchor_list].short_audio + "&quot;"
                        anchorListStr +=  ")'>"
                        anchorListStr +=  "<img src='./img/optional/play.png' />"
                        anchorListStr += "</span>"
                        anchorListStr += "<span class='list-user-info'><div>"
                        anchorListStr += "<span class='preferred'>优选</span>"
                        anchorListStr += "<span class='stars'>" + "<img src='./img/optional/stars.png'>"
                        anchorListStr += "<span>" + data[anchor_list].scorenum + "</span></span></div></span>"
                        anchorListStr += "<span class='sex'>"
                        if(data[anchor_list].sex == 1){
                            anchorListStr += "<span><img src='./img/optional/sex-man-img.png'></span></span>"
                        }else if(data[anchor_list].sex == 2){
                            anchorListStr += "<span><img src='./img/optional/sex-woman-img.png'></span></span>"
                        }
                        anchorListStr += "<span class='userInfo'  style='margin-left: 6px;'>"
                        anchorListStr += "<span id='username' style='margin-left: 0;'>" + data[anchor_list].nickname + "</span>"
                        anchorListStr += "<div id='ordertime'>服务" + "<span style='color: #ea3f2a'>" + data[anchor_list].ordertime
                        anchorListStr += "</span>次数</div></span>"

                        anchorListStr += "<span class='anchor-tag'>"
                        var label = data[anchor_list].label
                        for(i in label){
                            anchorListStr += "<span style='margin: 0 3px;'>" + label[i] + "</span>"
                        }
                        anchorListStr += "</span></span>"

                        var str = ''
                        str = data[anchor_list].uuid;
                        anchorListStr += "</span><span class='list-service-radio' style='margin-right:11px;' onclick='payProcess.selectAnchor(this,"+ "&quot;" + str + "&quot;" + ")'>"

                        if(_this.uuid == data[anchor_list].uuid){
                            anchorListStr += "<img class='select-btn' src='./img/optional/checked-btn.png'>"
                        }else{
                            anchorListStr += "<img class='select-btn' src='./img/optional/unchecked-btn.png'>"
                        }



                        anchorListStr += "<i style='display:none;'>"+ str + "</i>"
                        anchorListStr += "</span></div>"
                    }
                    if(anchor_list == 0){
                        miss = setTimeout(function(){
                            countDown(countTime,'process-bar')
                            $('#process-bar').show()
                        },120000)

                        $('.anchors-list-content').empty()
                        $('.anchors-list-content').append(anchorListStr)
                    }else{
                        console.log(anchorListStr)
                        console.log($('.select-btn').find('audio').length)
                        console.log(SelectFlag)
                       if($('.select-btn').find('audio').length == 0 && SelectFlag == false){
                            $('.anchors-list-content').empty()
                            $('.anchors-list-content').append(anchorListStr)
                            // SelectFlag = true
                        } else{
                            $('#anchorSound').bind('ended',function () {
                                $('.anchors-list-content').empty();
                                $('.anchors-list-content').append(anchorListStr)
                            });
                        }
                    }
                    var len = $('.anchors-list-detail').length
                    if(len > 3){
                        $('.anchors-list-content').css({
                            'overflow': 'scroll',
                            'overflow-x': 'hidden'
                        })
                    }
                    $('.mask_pay_select').show().siblings().hide()
                }
            }
        },20000)
    },
    reajax: function(){
        var _this = this
         reajax = setInterval(function(){
            $.ajax({
                url: 'http://zb.heardtech.com/Put/Recordinformation ',
                type: 'post',
                dataType: 'json',
                data: {
                    uuid: _this.oid
                },
                success: function(data){
                    console.log(data)
                },
            })
        },20000)
    },
    // 获取主播列表
    anchorList: function(type) {
        var _this = this
        $.ajax({
            url: apiCollect.apiPostChoseOrder,
            type: 'post',
            dataType: 'json',
            data: {
                type: type,
                token: localStorage.getItem('token'),
                oid: _this.oid,
            },
            success: function(data){
                $('.anchors-list-content').empty();
                _this.uuid = ''
                var anchorListStr = ''
                for( anchor_list in data.data.list){
                    // 渲染列表
                    anchorListStr += "<div class='anchors-list-detail' onclick='payProcess.test(this)'>"
                    anchorListStr += "<span class='list-play-btn' onclick='payProcess.playSound(this,"+ "&quot;" + data.data.list[anchor_list].short_audio + "&quot;"
                    anchorListStr +=  ")'>"
                    anchorListStr +=  "<img src='./img/optional/play.png' />"
                    anchorListStr += "</span>"
                    anchorListStr += "<span class='list-user-info'><div>"
                    anchorListStr += "<span class='preferred'>优选</span>"
                    anchorListStr += "<span class='stars'>" + "<img src='./img/optional/stars.png'>"
                    anchorListStr += "<span>" + data.data.list[anchor_list].scorenum + "</span></span></div></span>"
                    anchorListStr += "<span class='sex'>"
                    if(data.data.list[anchor_list].sex == 1){
                        anchorListStr += "<span><img src='./img/optional/sex-man-img.png'></span></span>"
                    }else if(data.data.list[anchor_list].sex == 2){
                        anchorListStr += "<span><img src='./img/optional/sex-woman-img.png'></span></span>"
                    }
                    anchorListStr += "<span class='userInfo' style='margin-left: 6px;'>"
                    anchorListStr += "<span id='username' style='margin-left: 0;'>" +  data.data.list[anchor_list].nickname + "</span>"
                    anchorListStr += "<div id='ordertime'>服务" + "<span style='color: #ea3f2a'>" + data.data.list[anchor_list].ordertime
                    anchorListStr += "</span>次数</div></span>"

                    anchorListStr += "<span class='anchor-tag'>"
                    var label = data.data.list[anchor_list].label
                    for(i in label){
                        anchorListStr += "<span style='margin: 0 3px;'>" + label[i] + "</span>"
                    }
                    anchorListStr += "</span></span>"

                    var str = ''
                    str = data.data.list[anchor_list].uuid;
                    anchorListStr += "</span><span class='list-service-radio' style='margin-right:11px;' onclick='payProcess.selectAnchor(this,"+ "&quot;" + str + "&quot;" + ")'>"
                    anchorListStr += "<img class='select-btn' src='./img/optional/unchecked-btn.png'>"
                    anchorListStr += "<i style='display:none;'>"+ str + "</i>"
                    anchorListStr += "</span></div>"
                }
                $('.anchors-list-content').append(anchorListStr)
                var len = $('.anchors-list-detail').length
                  if(len > 3){
                        $('.anchors-list-content').css({
                            'overflow': 'scroll',
                            'overflow-x': 'hidden'
                        })
                }
                $('.mask_pay_select').show().siblings().hide()
            },
            error: function(data){
                console.log(data.code)
            }
        })
        $('.anchors-list-type').find('span').removeClass('list-type-active')
        if(type == 0){
            $('.anchors-list-type').find('span').eq(0).addClass('list-type-active')
        }else if(type == 1){
            $('.anchors-list-type').find('span').eq(1).addClass('list-type-active')
        }else {
            $('.anchors-list-type').find('span').eq(2).addClass('list-type-active')
        }
    },
    // 选择主播
    selectAnchor: function(that,uuid){
        var _this = this;
        var $this=$(that);
        $('.select-btn').attr('src','./img/optional/unchecked-btn.png')
        if(flag == false){
            _this.uuid = uuid
            $this.find('.select-btn').attr('src','./img/optional/checked-btn.png')
        }
    },
    test(that){
        $that = $(that)
        var btn = $that.find('.list-service-radio')
        var uuid = $that.find('.list-service-radio').find('i').text()
        flag = false
        payProcess.selectAnchor(btn,uuid)
    },
    // 播放音乐
    playSound: function(that,sound){
        var _this = this;
        var $this=$(that);
        var play = localStorage.setItem('sound', sound);
        if($this.find('audio').length == 0){
            SelectFlag = true
            $this.find('img').attr('src','./img/optional/play.gif')
            $this.parent('.anchors-list-detail').siblings().find('.list-play-btn').find('img').attr('src','./img/optional/play.png')
            $this.parent('.anchors-list-detail').siblings().find('.list-play-btn').find('audio').remove()
            $this.append('<audio id="anchorSound" src="' + localStorage.getItem('sound') + '" style="display:none" autoplay/>')
            $('#anchorSound').bind('ended',function () {
                $this.find('audio').remove();
                $('.anchors-list-content').empty();
                $('.anchors-list-content').append(anchorListStr)
            });
        }else {
            SelectFlag = false
            $this.find('audio').remove();
            $this.find('img').attr('src','./img/optional/play.png')
            // $('.anchors-list-content').empty();
            // $('.anchors-list-content').append(anchorListStr)
            var len = $('.anchors-list-detail').length
            if(len > 3){
                $('.anchors-list-content').css({
                    'overflow': 'scroll',
                    'overflow-x': 'hidden'
                })
            }
        }
    },
    // 选定主播
    confirmAnchor: function(){
        var _this = this

        if( _this.uuid != '' && flag == false ){
            console.log(_this.uuid)
           flag = true
            $.ajax({
                url: apiCollect.apiPostSelectChoseUse,
                type: 'post',
                dataType: 'json',
                data: {
                    uuid: _this.uuid,
                    token: localStorage.getItem('token'),
                    oid: _this.oid
                },
                success: function(data){
                    if(data.code == '000000'){
                        $('.mask_pay_three').show().siblings().hide()
                        $('.mask_pay_three .ok_info').text('下单成功')
                        $('.mask_pay_three .mask_finish').find('img').css({
                            'margin': '40px 134px 24px 133px'
                        });
                        $('#selectInfo-scorenum').text(data.data.scorenum)
                        if(data.data.sex == 1){
                            $('.info-sex').html('<img src="./img/optional/sex-man-img.png">')
                        }else if(data.data.sex == 2){
                            $('.info-sex').html('<img src="./img/optional/sex-woman-img.png">')
                        }
                        $('#info-username').text(data.data.nickname)
                        $('#info-ordertime').text(data.data.ordertime)
                        var label = data.data.label
                        for(i in label){
                            $('.info-tag').append("<span style='margin: 0 2px;'>" + label[i] + "</span>" )
                        }
                        $('.mask_pay_three').find('.ishose1').show()
                        $('.mask_pay_three').find('.ishose0').hide()


                        $('#mask_close').show()
                        $('.order_head').removeClass('col585858').addClass('colacacac')
                        $('.final').addClass('col585858')
                        $('.anchors-list-content').empty()
                        _this.anchor_num = 0
                        clearTimeout(miss)
                        _this.uuid = "";
                    }else {
                        headtipObj.show(data.message);
                    }
                },
                error: function(data){
                    console.log(data)
                }
            })
        }else{
            _this.uuid != ''
            _this.ajaxLock == false
        }
    },

};
payProcess.init(token);

// 标题回车 跳转到内容
$('#document-wrapper .header input').on('keydown', function(ev) {
    if (ev.keyCode == 13) {
        ev.preventDefault();
        $('#document-wrapper .content .text-wrapper').focus();
    }
});
$('#document-wrapper .header input').on('input propertychange', function(ev) {
    ev.preventDefault();
    if ($(this).val()) {
        $('.header>div').removeClass('hide')
    } else {
        $('.header>div').addClass('hide')
    }
})
$('.sign_email').keypress(function() {
    var $this = $(this);
    var $container = $('.sign_e');
    if ($container.hasClass('active')) {
        $this.text('修改');
        $container.removeClass('active');
        $('.sign_email').addClass('hide');
        $('.sign_e span').show().text($('.sign_email').val());
    } else {
        $this.text('确认');
        $container.addClass('active');
        $('.sign_e span').hide();
        $('.sign_email').removeClass('hide');
    }
});
$('#mask_email').keypress(function() {
    var $this = $(this);
    var $container = $('.mask_footer_e');
    if ($container.hasClass('active')) {
        $this.text('修改');
        $container.removeClass('active');
        $('#mask_email').addClass('hide');
        $('.mask_footer_e span').show().text($('#mask_email').val());
    } else {
        $this.text('确认');
        $container.addClass('active');
        $('.mask_footer_e span span').hide();
        $('#mask_email').removeClass('hide');
    }
});
$('.speed_wrapper input[type="radio"]').click(function(ev) {
    var $this = $(this);
    var value = $this.val();
    var $switcher = $('.speed_wrapper .switch');
    if (value == '0') {
        $switcher.css('left', '-1px');
    }
    if (value == '1') {
        $switcher.css('left', '54px');
    }
    if (value == '2') {
        $switcher.css('left', '110px');
    }
});
$('#document-wrapper .content').click(function() {
    $('.text-wrapper').get(0).focus();
});
// 下单
var orderFunc = {
    price: 0,
    // 获取ajax需要的所有字段
    getAllData: function(oid) {
        return {
            token: localStorage.getItem('token'),
            oid: GetQueryString("oid") ? GetQueryString("oid") : 0,
            title: $('#document-title').val(),
            article: $('.text-wrapper').html(),
            demand: this.getVolType(),
            urgent: this.getQuickBool() ? 1 : 0,
            soundtype: this.getBroadcastType(),
            sex: this.getGender(),
            speed: this.getSpeed(),
            level: this.getUserLv(),
            day: timeSelector.value[0],
            hour: timeSelector.value[1],
            minute: timeSelector.value[2],
            readtitle: payProcess.readtitle,
            bgmtype: $('.selecterP .musicType').text(), //0 否 1 系统bgm 2 用户自己上传bgm
            bgmid: $('.selecterP .musicId').text(), //bgm对应id
            ischose: ischose
        }
    },
    // 获取播音速度
    getSpeed: function() {
        return $('.speed_wrapper input[type="radio"]:checked').val();
    },
    // 获取性别
    getGender: function() {
        // return $('.service_check.sox_bg').data('sex');
        return $('.gender_wrapper input[type="radio"]:checked').val();
    },
    // 获取输入字数
    getInputTextLength: function() {
        var text = $('#document-wrapper .text-wrapper').text()
        // 去除空格
        text = text.replace(/\s+/g, '');
        return text.length;
    },
    // 获取主播等级
    getUserLv: function() {
        return $('.footer_auther_li .footer_auther_lis .footer_li_name.footer_yes').data('lv');
    },
    // 获取是否加急
    getQuickBool: function() {
        return $('input.footer_checked').prop('checked');
    },
    // 获取配音类型 极速 预约
    getVolType: function() {
        return $('#voice').attr('data-type');
    },
    // 获取需要的主播等级
    getAchorLv: function() {
        return parseInt($('#footer_auther_check').attr('data-lv'));
    },
    // 获取播报类型
    getBroadcastType: function() {
        return $('#broacast-type .service_lisen').data('type');
    },
    // 计算输入的输入的价钱
    // volType 配音类型
    // quickBool 是否加急
    // achorLv 主播等级
    // textLen 文章字数
    // var totalPrice,basicPrice,urgentPrice,originPrice,bgMusicPrice,subscribePrice
    getPrice: function(volType, quickBool, achorLv, textLen,origin) {
        var price = 0;
         originPrice = basicPrice * 0.2
        var textLen = this.getInputTextLength(); // 输入字数
        if (textLen < 500) {
            textLen = 500;
        }
        var priceUnit = calVars.priceUnit[achorLv]; // 各个主播级别价格单价
        // 基础价格
        basicPrice = priceUnit * Math.ceil(textLen / 100)
        originPrice = basicPrice * 0.2
        var discount = 1; // 折扣
        if (volType == 3) {
            // 预约配音
            $('.mode-text').text('预约')
            discount = calVars.preDiscount;
            price = basicPrice * discount
            subscribePrice = basicPrice * 0.2
            if(ischose == 1){
                price += originPrice
            }else{
                originPrice= 0
            }
            totalPrice = price
            // 预约无加急
            urgentPrice = 0
        } else {
            subscribePrice = 0
            if (quickBool) {
                // 加急单
                discount = calVars.quickDiscount;
                price = basicPrice * discount;
                urgentPrice = 0.5 * basicPrice
                if(ischose == 1){
                    price += originPrice
                }else{
                    originPrice = 0
                }
            } else {
                // 普通单
                $('.mode-text').text('极速')
                price = basicPrice * discount;
                urgentPrice = 0
                if(ischose == 1){
                    price += originPrice
                }else{
                    originPrice = 0
                }
            }
        }
        if (volType == 4) {
            $('.mask_older_deep').css('margin-left','83px')
            $('.mode-text').text('签约')

            price = basicPrice * discount;
        }
        totalPrice = parseFloat(price.toFixed(2))
        return  price.toFixed(2)
    },
    getTime: function(volType, quickBool, textLen) {
        var time = 0;
        var timeUnit = 0; // 时间单位
        var timeBase = 0; // 基础时长
        if (volType == 3) {
            // 预约配音
            timeUnit = calVars.preTimeUnit;
            timeBase = calVars.preTime;
        } else {
            if (quickBool) {
                // 加急单
                timeUnit = calVars.quickTimeUnit;
                timeBase = calVars.quickTime;
            } else {
                // 普通单
                timeUnit = calVars.normalTimeUnit;
                timeBase = calVars.normalTime;
            }
        }
        // var host2 = 'http://testmedia.heardtech.com';
        var host2 = 'http://media.soundems.com';
        // 再次下单
        var apiCollect2= {
            apiPostChoseOrder2: host2 + '/Post/chosereorder'
        }
        var oid = GetQueryString("oid")
        if(oid){
            $.ajax({
                    url: apiCollect2. apiPostChoseOrder2,
                    type: 'post',
                    dataType: 'json',
                    data: {
                        token: localStorage.getItem('token'),
                        oid: oid
                    },
                    success: function(data){
                       if(data.code == 000000){
                              timeBase = data.data.circulationtime
                        }else{
                            // headtipObj.show(data.message);
                            window.location.href = './speeDdubbing.html'
                        }

                    },
                    error: function(data){
                        console.log(data.data)
                    }
                })
        }
        time = timeBase + timeUnit * Math.ceil(textLen / 100);
        return time;
    },
    updateHTML: function() {
        var showTextLen = this.getInputTextLength(); // footer word文章字数
        var textLen = this.getInputTextLength(); // 文章字数
        var volType = this.getVolType(); // 配音类型
        var quickBool = this.getQuickBool(); // 是否加急
        var achorLv = this.getAchorLv(); // 主播等级
        var price; // 价格
        if ($('#selShowHide').hasClass('hide')) {
            price = parseFloat(this.getPrice(volType, quickBool, achorLv, textLen));
            bgMusicPrice = 0
        } else {
            bgMusicPrice = 20
            price = parseFloat(this.getPrice(volType, quickBool, achorLv, textLen)) + 20
        }
        this.price = price.toFixed(2);
        totalPrice = price
        var time = this.getTime(volType, quickBool, textLen); // 时间
        $('#footer .footer_wrap .left .footer_word_num').text(showTextLen); // 更新字数·
        $('#mask_money_count').text('￥' + price.toFixed(2)); // 更新弹窗价格
        var discount = price * 0.35;
        $('#mask_discount').text(" " + discount.toFixed(2) + " ");
        // 更新弹窗原价
        $('#mask_money_origin').text("￥ " + Math.ceil(price / 0.7) + '.00' + " ");
        if (textLen == 0) {
            price= 0
            totalPrice = 0
            basicPrice = 0
            urgentPrice = 0
            originPrice = 0
            bgMusicPrice = 0
            subscribePrice = 0
            if (volType == 1) {
                flag = true
                $('.footer_rmb').html("￥ 0" + '<span>＞</span>'); // 更新价格
                $('.footer_time_d').text('(按字数自动计时)');
                $('.footer_time_num_wrapper').html('<span class="left">耗时<strong class="footer_time_num">0</strong>分钟</span>'); // 更新时间
            } else if (volType == 3) {
                flag = true
                $('.footer_rmb').html("￥ 0" + '<span>＞</span>'); // 更新价格
                $('.footer_time_d').text('(按字数自动计时)');
                var r = timeSelector.getHours();
                $('.footer_time_num_wrapper').html('<span class="left">预约<strong class="footer_time_num">' + r + '</strong>小时</span>'); // 更新时间
            }
            // $('.footer_rmb').text("￥ 0");    // 更新价格
            if (volType == 4) {
                flag = false
                basicPrice = 0
                totalPrice = 0
                $('.footer_rmb').html(calVars.words)
            }

            if (!$('#selShowHide').hasClass('hide')) {
                $('.footer_rmb').html("￥ 20" + '<span>＞</span>');
            }
        } else {
            $('.footer_rmb').html("￥ " + price.toFixed(2) + '<span>＞</span>'); // 更新价格
            // $('.footer_time_num').text(Math.floor(time / 60s)); // 更新时间
            if (volType == 1) {
                flag = true
                var endTime = new Date();
                endTime.setMinutes(endTime.getMinutes() + Math.floor(time / 60));
                var minutes = endTime.getMinutes() < 10 ? '0' + endTime.getMinutes() : endTime.getMinutes();
                $('.footer_time_d').text('(大约 ' + endTime.getHours() + ':' + minutes + ' 送达)');
                $('.footer_time_num_wrapper').html('<span class="left">耗时<strong class="footer_time_num">' + Math.floor(time / 60) + '</strong>分钟</span>'); // 更新时间
            } else if (volType == 3) {
               flag = true
                var value = timeSelector.value;
                var dayArr = ['今天', '明天', '后天'];
                $('.footer_time_d').text('(' + dayArr[value[0] - 1] + ' ' +
                    (value[1] >= 10 ? value[1] : '0' + value[1]) + ":" +
                    (value[2] >= 10 ? value[2] : '0' + value[2]) + ' 送达)');
                var r = timeSelector.getHours();
                $('.footer_time_num_wrapper').html('<span class="left">预约<strong class="footer_time_num">' + r + '</strong>小时</span>'); // 更新时间
            }
            if (volType == 4) {
                flag = false
                basicPrice = 0
                totalPrice = 0
                $('.footer_rmb').html(calVars.words)
            }
        }
        if (volType == 4) {
            flag = false
            basicPrice = 0
            totalPrice = 0
            $('.footer_rmb').html(calVars.words)
        }
        finalType = volType
    }
};


$('#document-wrapper .content .text-wrapper').on('keyup paste', function(ev) {
    setTimeout(function() {
        orderFunc.updateHTML();
        if(flag != false && orderFunc.getInputTextLength() != 0){
            $('.footer_rmb').html("￥ " + totalPrice.toFixed(2)+ '<span>＞</span>');
            $('.footer_rmb').hover(function() {
                // 总价
                // $('.footer_rmb').text("￥ " + totalPrice.toFixed(2))
                $('.total-price').text(totalPrice.toFixed(2))
                $('.basic-price').text(basicPrice.toFixed(2))
                $('.urgent-price').text(urgentPrice.toFixed(2))
                $('.origin-price').text(originPrice.toFixed(2))
                $('.bg-music-price').text(bgMusicPrice.toFixed(2))
                // 预约
                $('.subscribe-price').text(subscribePrice.toFixed(2))
                $('.total-info').show()
            }, function() {
                $('.total-info').hide()
            })
        }else{
        }
    }, 0)
});

$('.service_head .bg-rule').click(function() {
    headtipObj2.show('播音话术功能即将推出尽情期待')
});

$(".mask_wrap .mask_cout").click(function(ev) {
    ev.stopPropagation();
});
$('.black_div').click(function(e) {
    e.stopPropagation();
    if ($('.begin').css('display') == 'none') {
        $('.begin').css({ 'display': 'block' });
        $(".black_div").addClass("activeBtn");
    } else {
        $(".black_div").removeClass("activeBtn");
        $('.begin').css({ 'display': 'none' })
    }
});
$('.black_div1').click(function(e) {
    e.stopPropagation();
    if ($('.begin1').css('display') == 'none') {
        $('.begin1').css({ 'display': 'block' });
        $(".black_div1").addClass("activeBtn");
    } else {
        $(".black_div1").removeClass("activeBtn");
        $('.begin1').css({ 'display': 'none' })
    }
});
$('.clickServer').click(function(e) {
    e.stopPropagation();
    if ($('.server').css('display') == 'none') {
        $('.server').css({ 'display': 'block' });
        $('.mine').css({ 'display': 'none' })
    } else {
        $('.server').css({ 'display': 'none' })
    }
});
$('.user_img').click(function(e) {
    e.stopPropagation();
    if ($('.mine').css('display') == 'none') {
        $('.mine').css({ 'display': 'block' });
        $('.server').css({ 'display': 'none' })
    } else {
        $('.mine').css({ 'display': 'none' })
    }
});
$(".setLike").click(function(e) {
    e.stopPropagation();
    $('.voidServer').addClass('none');
    $('.setLover').removeClass('none');
    $(".setLike").siblings().find("a").removeClass('active');
    $(".setLike a").addClass("active");
    $(".setLike a img").attr('src', 'img/setChoose.png');
    $(".left_list").find('li').first().find('a').find('img').attr('src', 'img/voiceServer.png');
    $('.transition').animate({ 'width': '100%' }, 500, function() {
        $('.transition').css({ 'width': "0px" });
    });
});
$(".left_list").find('li').first().click(function(e) {
    e.stopPropagation();
    $('.voidServer').removeClass('none');
    $('.setLover').addClass('none');
    $(".left_list").find('li').first().siblings().find("a").removeClass('active');
    $(".left_list").find('li').first().find('a').addClass("active");
    $(".setLike a img").attr('src', 'img/little_logo_10.png');
    $(".left_list").find('li').first().find('a').find('img').attr('src', 'img/little_logo_03.png');
    $('.transition').animate({ 'width': '100%' }, 500, function() {
        $('.transition').css({ 'width': "0px" });
    });
});
$('.maskChooseList .point.double').click(function(e) {
    e.stopPropagation();
    if ($(e.target).attr('src') == 'img/maskChoose.png') {
        $(e.target).attr('src', 'img/maskUnchoose.png')
    } else {
        $(e.target).attr('src', 'img/maskChoose.png')
    }
});
$(".myMask").click(function(e) {
    e.stopPropagation();
    $(".myMask").addClass("none");
});
$('.headerLeft.left').click(function(e) {
    e.stopPropagation();
    $('.voidServer').removeClass('none');
    $('.setLover').addClass('none');
    $(".left_list").find('li').first().siblings().find("a").removeClass('active-list');
    $(".left_list").find('li').first().find('a').addClass("active-list");
    $(".setLike a img").attr('src', 'img/little_logo_10.png');
    $(".left_list").find('li').first().find('a').find('img').attr('src', 'img/little_logo_03.png');
    $('.transition').animate({ 'width': '100%' }, 500, function() {
        $('.transition').css({ 'width': "0px" });
    });
});
$('.maskChooseList .point.single').click(function(e) {
    e.stopPropagation();
    if ($(e.target).attr('src') == 'img/maskChoose.png') {
        $(e.target).attr('src', 'img/maskUnchoose.png');
    } else {
        $(e.target).parent().siblings().find('img').attr('src', 'img/maskUnchoose.png');
        $(e.target).attr('src', 'img/maskChoose.png')
    }
});
$(".maskcancle").click(function(e) {
    e.stopPropagation();
    $(".myContent").addClass('none');
    $(".myMask").addClass('none');
});
$(".saveBtn").click(function(e) {
    e.stopPropagation();
    $(".myContent").addClass('none');
    $(".myMask").addClass('none');
});
$('.clickMusic').click(function(e) {
    e.stopPropagation();
    $(".myMask").removeClass('none');
    $(".myContent").addClass('none');
    $(".music").removeClass('none');
});
$('.clickFileHeader').click(function(e) {
    e.stopPropagation();
    $(".myMask").removeClass('none');
    $(".myContent").addClass('none');
    $(".fileHeader").removeClass('none');
});
$('.clickSex').click(function(e) {
    e.stopPropagation();
    $(".myMask").removeClass('none');
    $(".myContent").addClass('none');
    $(".sex").removeClass('none');
});
$('.clickSpeakType').click(function(e) {
    e.stopPropagation();
    $(".myMask").removeClass('none');
    $(".myContent").addClass('none');
    $(".speakType").removeClass('none');
});
$('.clickSpeakSpeed').click(function(e) {
    e.stopPropagation();
    $(".myMask").removeClass('none');
    $(".myContent").addClass('none');
    $(".speakSpeed").removeClass('none');
});
$('.clickSpeakNeed').click(function(e) {
    e.stopPropagation();
    $(".myMask").removeClass('none');
    $(".myContent").addClass('none');
    $(".speakNeed").removeClass('none');
});
$('.clickSpeakerLove').click(function(e) {
    e.stopPropagation();
    $(".myMask").removeClass('none');
    $(".myContent").addClass('none');
    $(".speakerLove").removeClass('none');
});
//遮罩
$('.mask_c_close').click(function() {
    $('.mask_wrap').hide();
});
$('#myemail').click(function() {
    $('.mask_wrap').show();
    $('.mask_w').show();
    $('.mask_up').hide();
});
$('#myfile').click(function() {
    $('.mask_wrap').show();
    $('.mask_w').hide();
    $('.mask_up').show();
});
$('#myemail1').click(function() {
    $('.mask_wrap').show();
    $('.mask_w').show();
    $('.mask_up').hide();
});
$('#myfile1').click(function() {
    $('.mask_wrap').show();
    $('.mask_w').hide();
    $('.mask_up').show();
});
$('.mask_t_l').click(function() {
    $('.mask_w').show();
    $('.mask_up').hide();
});
$('.mask_t_r').click(function() {
    $('.mask_w').hide();
    $('.mask_up').show();
});

$("body").click(function() {
    $(".begin").css({ "display": "none" });
    $('.server').css({ "display": "none" });
    $(".mine").css({ 'display': "none" });
    $(".black_div").removeClass("activeBtn");
    $(".mask_wrap").hide();
});

$('#custom-time').click(function() {
    timeSelector.show();
});
var timeSelector = {
    $container: $('#time-selector'),
    value: [0, 0, 0],
    defaultTime: '',
    confirmed: false,
    init: function(callback) {
        this.initOptions();
        this.initVal();
        this.bindClose();
        this.bindShowOptions();
        this.bindConfirm(callback);
    },
    getHours: function() {
        if (this.confirmed) {
            // 转换成小时
            var value = this.value;
            var nDate = this.defaultTime;
            var rDate = new Date();
            rDate.setDate(rDate.getDate() + value[0] - 1);
            rDate.setHours(value[1]);
            rDate.setMinutes(value[2]);
            var r = (rDate - nDate) / 1000 / 60 / 60;
            if (isFloat(r)) r = r.toFixed(1);
            if (r <= 3) r = 3;
            return r;
        } else {
            // 如果是默认，则永远为三个小时
            return 3;
        }
    },
    bindClose: function() {
        var _this = this;
        this.$container.find('.close').click(function(ev) {
            _this.close();
        })
    },
    bindConfirm: function(callback) {
        var _this = this;
        _this.$container.find('.btn.btn-confirm').click(function() {
            _this.confirm(callback);
        })
    },
    bindShowOptions: function() {
        var _this = this;
        _this.$container.find('.select-wrapper .container').click(function(ev) {
            ev.stopPropagation();
            var $this = $(this),
                $list = $this.siblings('.list-wrapper');
            $list.parents('.select-wrapper').siblings().find('.list-wrapper').addClass('hide');
            if ($list.hasClass('hide')) {
                $list.removeClass('hide');
            } else {
                $list.addClass('hide');
            }
        });
        _this.$container.click(function() {
            // 点击内容 关闭所有选项
            _this.$container.find('.list-wrapper').addClass('hide');
        });
        _this.$container.delegate('ul.list li', 'click', function(ev) {
            var $this = $(this),
                val = $this.text();

            $this.parents('.list-wrapper').siblings('.container').find('span').text(val);
        });
        _this.$container.delegate('.day-wrapper ul.list li', 'click', function(ev) {
            // 修改日期 则同时修改时
            var $this = $(this);
            _this.resetHourListOnDay($this.text());
        })
    },
    close: function() {
        this.$container.addClass('hide');
    },
    resetHourListOnDay: function(day) {
        var html = '';
        var hourStart = (new Date()).getHours();
        if (day == '今天') {
            for (var i = hourStart + 3; i < 24; i++) {
                html += '<li>' + i + '</li>';
            }
            // 如果选择的小时不对 则重置
            var selectedHour = parseInt(this.$container.find('.hour-wrapper .container > span').text());
            if (selectedHour < hourStart) {
                this.$container.find('.hour-wrapper .container > span').text(hourStart);
            }
        } else {
            for (var i = 0; i < 24; i++) {
                html += '<li>' + i + '</li>';
            }
        }
        this.$container.find('.hour-wrapper ul.list').html(html);
    },
    resetValue: function() {
        var dt = new Date(),
            day = dt.getDay(),
            hour = dt.getHours() + 3,
            minutes = dt.getMinutes();
        var value = [1, hour, minutes];
        if (hour > 23) {
            value[0] = 2;
            value[1] = hour - 23;
        }
        this.value = value;
    },
    initVal: function() {
        var dayText = ['今天', '明天', '后天'];
        this.resetValue();
        if (!this.confirmed) {
            this.$container.find('.day-wrapper .container span').text(dayText[this.value[0] - 1]);
            this.$container.find('.hour-wrapper .container span').text(this.value[1]);
            this.$container.find('.minute-wrapper .container span').text(this.value[2]);
            this.resetHourListOnDay(dayText[this.value[0] - 1]);
        }
    },
    initOptions: function() {
        var dayHTML = '',
            hourHTML = '',
            minuteHTML = '';
        var hourStart = (new Date()).getHours();

        var item;
        var days = ['今天', '明天', '后天'];
        for (item in days) {
            dayHTML += "<li>" + days[item] + "</li>";
        }
        for (item = hourStart + 3 ; item < 24; item++) {
            hourHTML += "<li>" + item + "</li>";
        }
        for (item = 0; item < 60; item++) {
            minuteHTML += "<li>" + item + "</li>";
        }

        this.$container.find('.day-wrapper ul.list').html(dayHTML);
        this.$container.find('.hour-wrapper ul.list').html(hourHTML);
        this.$container.find('.minute-wrapper ul.list').html(minuteHTML);
    },
    show: function() {
        this.initVal();
        this.$container.removeClass('hide')

    },
    getValue: function() {
        var dayObj = {
            '今天': 1,
            '明天': 2,
            '后天': 3
        };
        var day = this.$container.find('.day-wrapper .container span').text(),
            hour = this.$container.find('.hour-wrapper .container span').text(),
            minute = this.$container.find('.minute-wrapper .container span').text();
        return [dayObj[day], parseInt(hour), parseInt(minute)];
    },
    confirm: function(callback) {
        var val = this.getValue();
        var dt = new Date(),
            day = dt.getDay(),
            hour = dt.getHours(),
            minutes = dt.getMinutes();
        if (val[0] == 1 && val[1] <= hour + 3 && val[2] < minutes) {
            // 小于3小时
            headtipObj.show('至少设置 3 小时 + 后')
        } else {
            this.defaultTime = new Date();
            this.confirmed = true;
            this.value = val;
            this.close();
            if (typeof callback == 'function') callback(this.value);
        }
    }
};
timeSelector.init(function(valueArr) {
    // 确定后的操作
    var textLen = orderFunc.getInputTextLength();
    if (textLen > 0) {
        var dayObj = {
            1: '今天',
            2: '明天',
            3: '后天'
        };
        var day = dayObj[valueArr[0]],
            hour = valueArr[1] < 10 ? '0' + valueArr[1] : valueArr[1],
            minute = valueArr[2] < 10 ? '0' + valueArr[2] : valueArr[2];
        var text = day + ' ' + hour + ':' + minute;
        // $('#custom-time span').text(text);
        $('.footer_time_d').text('(' + text + ' 送达' + ')');
        orderFunc.updateHTML();
    } else {
        // $('.footer_time_d').text('(按字数自动计时)');
        orderFunc.updateHTML();
    }
});
// 设置改变主体项
pressSelect.init();

// 按钮tip
$('.hover-show-tip').mouseover(function(e) {
    e.stopPropagation();
    var $this = $(this);
    var $tipContainer = $('#tip-container');
    if ($tipContainer.length == 0) {
        $('body').before('<div id="tip-container"><span class="arrow"></span><span class="content"></span></div>')
    }
    $tipContainer.find('.content').text($this.data('tip'));
    var top = $this.offset().top + 40,
        left = $this.offset().left + ($this.width() - $tipContainer.width()) / 2 - 4;
    $tipContainer.find('.arrow').css({
        left: $tipContainer.width() / 2 - 3
    });
    $tipContainer.css({
        position: 'fixed',
        left: left,
        zIndex: 4000
    }).show();
});
$('.hover-show-tip').mouseleave(function() {
    var $tipContainer = $('#tip-container');
    $tipContainer.hide()
});

//签约订单
//弹框位置
var $awb = $('#allWrapBlack');
var $warehouse = $('#warehouse');
var $cusTip = $('.customTip');
var $musicTab = $('.musicTab');
var $allClose = $('.allClose');
var $uploading = $('#uploading');

var mh = $warehouse.outerHeight();
var mw = $warehouse.outerWidth();
var wh = $(document).height();
var ww = $(document).width();
$warehouse.css({
    'top': (wh - mh) / 2 + 'px',
    'left': (ww - mw) / 2 + 'px'
});
var uh = $uploading.outerHeight();
var uw = $uploading.outerWidth();
$uploading.css({
    'top': (wh - uh) / 2 + 'px',
    'left': (ww - uw) / 2 + 'px'
});
$(window).resize(function() {
    var mh = $warehouse.outerHeight();
    var mw = $warehouse.outerWidth();
    var uh = $uploading.outerHeight();
    var uw = $uploading.outerWidth();
    var wh = $(document).height();
    var ww = $(document).width();
    $warehouse.css({
        'top': (wh - mh) / 2 + 'px',
        'left': (ww - mw) / 2 + 'px'
    });
    $uploading.css({
        'top': (wh - uh) / 2 + 'px',
        'left': (ww - uw) / 2 + 'px'
    })
});






var borcastVal = 0
$('#broacast-type').delegate('div.option', 'click', function(ev) {
    ev.stopPropagation();
    ev.preventDefault();
    var $this = $(this);
    var val = $this.data('value');
    var text = $this.text();
    borcastVal = val
    console.log(borcastVal)
    $('.customTip>ul').children().eq(borcastVal).trigger('click')

    $('#broacast-type .service_lisen').attr('data-type', val).text(text);
    $('#broadcast-type-select').addClass('hide');
});
//音乐弹版
var musicAle = {
    type: 0, //0全部,1已传
    cid: 0,
    mid: token,
    getBgmData: {
        bgmType: '',
        bgmId: ''
    },
    init: function() {
        var _this = this;
        _this.allClose();
        _this.selectType();
        _this.closeSelectType();
        _this.tabMusic();
        _this.tabListType();
        _this.tabUploading();
        _this.tabMusic();
        _this.pullMusicList();
        _this.selectMusiType();
        _this.pullMusicClass1();
        _this.pullMusicClass2();
        _this.selectMusic1();
        _this.selectMusic2();
        _this.removerTopBgm();
        _this.wakeUp();
    },
    wakeUp: function() {
        //顶端选项呼出 音乐面板
        $('.service_head .bg-music').click(function(e) {
            e.stopPropagation();
            var _this = this

            $('.btns>.custom>span>span').text($('.customTip>ul>li').eq(borcastVal).children('.check').text());

            // console.log($('.customTip>ul>li').eq(borcastVal).children('.check').text())

            $('.saveBtn').removeClass('btn-black');


            $musicTab.children('div').eq(0).addClass('musicTabActive').siblings().removeClass('musicTabActive');
            $('.musicContent ul').eq(0).removeClass('hide').siblings().addClass('hide');
            if ($warehouse.hasClass('hide')) {
                $warehouse.removeClass('hide');
                $awb.removeClass('hide');
            } else {
                $warehouse.addClass('hide');
                $awb.addClass('hide');
            }
        });
    },
    allStopMusic: function() {
        for (var i = 0; i < $('.musicContent>ul>li>audio').length; i++) {
            $('.musicContent>ul>li>audio').get(i).pause()
        }
    },
    allClose: function() {
        //关闭按钮
        var _this = this;
        $allClose.click(function(e) {
            e.stopPropagation();
            if ($('#selShowHide').hasClass('hide')) {
                $('#new').removeClass('hide');
            } else {
                $('#new').addClass('hide');
            }
            $warehouse.addClass('hide');
            $uploading.addClass('hide');
            $awb.addClass('hide');
            // $('.btns>.custom>span').text('适合讲述');
            $(".music_upload_text").text('自定义背景音乐');
            // _this.cid = 0;
            _this.allStopMusic();
            $('.musicContent>ul>li>img').attr('src', 'img/playMusic.png');
            $('.musicContent>ul>li>input').prop('checked', false)
        });
    },
    selectType: function() {
        //音乐弹版左下角类型选择弹版
        $('.btns .custom').click(function(e) {
            e.stopPropagation();
            if ($cusTip.hasClass('hide')) {
                $cusTip.removeClass('hide')
            } else {
                $cusTip.addClass('hide')
            }
        });
    },
    closeSelectType: function() {
        //音乐弹版下点击隐藏了左下角选择框
        $warehouse.click(function(e) {
            e.stopPropagation();
            $cusTip.addClass('hide')
        });
    },

    selectMusiType: function() {
        //音乐弹版左下角 选择后 内容覆盖
        var _this = this;
        $('.customTip>ul').on('click', 'li', function() {
            var $this = $(this);
            $('.btns>.custom>span>span').text($this.children('.check').text());
            var j = $this.children('.hide').text();


            _this.cid = j;


            $('.musicContent').scrollTop(0);
            _this.pullMusicClass1();

        });


        $('.customTip>ul').on('mouseenter', 'li', function() {
            $(this).css('background', '#e5e5e5').siblings().css('background', '')
        });
        $('.customTip>ul').on('mouseleave', function() {
            $(this).children('li').css('background', '')
        })
    },
    tabListType: function() {
        //两个列表的切换
        var _this = this;
        $musicTab.children('div').click(function() {
            var $this = $(this);
            var i = $this.index();
            $this.addClass('musicTabActive').siblings().removeClass('musicTabActive');
            $('.musicContent').scrollTop(0);
            $('.musicContent ul').eq(i).removeClass('hide').siblings().addClass('hide');
            if (i == 1) {
                $('.btns .custom').hide();
                _this.pullMusicClass2();
                if (!$('.musicBox2 li').length) {
                    $('#noList').removeClass('hide');
                } else {
                    $('#noList').addClass('hide');
                }
            } else {
                $('.btns .custom').show().css('marginTop', '1px');
                $('#noList').addClass('hide');
            }
        });
    },
    tabUploading: function() {
        //音乐弹版下 呼出上传弹版
        var _this = this;
        $('#warehouse>.musicNav>div').eq(1).click(function() {
            $warehouse.addClass('hide');
            $uploading.removeClass('hide');
            $(".music_upload_text").text('自定义背景音乐');
            _this.allStopMusic()
        });
    },
    tabMusic: function() {
        //上传弹版下 呼出音乐弹版
        $('#uploading>.musicNav>div').eq(0).click(function() {
            $warehouse.removeClass('hide');
            $uploading.addClass('hide');
            $(".music_upload_text").text('自定义背景音乐');
        });
    },
    pullMusicList: function() {
        var _this = this;
        $.get(apiCollect.apiGetMusicType, {}, function(data) {
            if (data.code == '000000') {
                var data = data.data;
                var html = '';
                $.each(data, function(i, item) {
                    html += '<li><span class="hide">' + item.id + '</span><span class="check">' + item.name + '</span></li>'
                });
                $('.customTip ul').html(html)
            }
        })
    },
    pullMusicClass1: function() {
        var _this = this;
        $.get(apiCollect.apiGetBgmList, {
            type: 0,
            cid: _this.cid,
            mid: _this.mid
        }, function(data) {
            if (data.code == '000000') {
                var data = data.data;
                var html = '';
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    html += '<li class="clearfix" data-type=' + item.bgmtype + " data-id=" + item.id + " data-bgmsrc=" + item.music + '><img class="play" src="img/playMusic.png"><p><span class="musicId hide">' + item.id + '</span><span class="musicType hide">' + item.bgmtype + '</span>' + item.name + '</p><audio src=""></audio><input class="musicCheck" type="checkbox"></li>'
                }
                $('.musicContent ul').eq(0).html(html)
            }
        })
    },
    pullMusicClass2: function() {
        var _this = this;
        $.get(apiCollect.apiGetBgmList, {
            type: 1,
            cid: _this.cid,
            mid: _this.mid
        }, function(data) {
            if (data.code == '000000') {
                var data = data.data;
                var html = '';
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    html += '<li class="clearfix" data-bgmsrc="' + item.music + '"><img class="play" src="img/playMusic.png"><p><span class="musicId hide">' + item.id + '</span><span class="musicType hide">' + item.bgmtype + '</span>' + item.name + '</p><audio src="' + item.music + '"></audio><input class="musicCheck" type="checkbox"></li>'
                }
                $('.musicContent ul').eq(1).html(html)
            }
        })
    },
    selectMusic1: function() {
        $('.musicContent>ul').eq(0).on('click', 'li', function() {
            var $this = $(this);
            var saveBtn = $('#warehouse .saveBtn');
            for (var j = 0; j < $('.musicContent .musicBox2 audio').length; j++) {
                $('.musicContent .musicBox2 audio')[j].pause();
            }
            if ($this.find('audio').attr('src') == '') {
                $this.find('audio').attr('src', $this.data('bgmsrc'));
                $this.children('audio').get(0).play();
                $this.children('img').attr('src', 'img/stopMusic.png');
                $this.children('.musicCheck').prop('checked', true);
                saveBtn.addClass('btn-black');
            } else {
                if ($this.children('audio').get(0).paused) {
                    $this.children('audio').get(0).play();
                    $this.children('img').attr('src', 'img/stopMusic.png');
                    $this.children('.musicCheck').prop('checked', true);
                    saveBtn.addClass('btn-black');
                } else {
                    $this.children('audio').get(0).pause();
                    $this.children('img').attr('src', 'img/playMusic.png');
                    $this.children('input').prop('checked', false);
                    saveBtn.removeClass('btn-black');
                }
            }

            //监听播放完毕 img回执
            $this.children('audio').get(0).addEventListener('ended', function() {
                $this.children('img').attr('src', 'img/playMusic.png');
                $this.children('input').prop('checked', false);
            }, false);
            var thisIndex = $this.index();
            for (var i = 0, len = $('.musicContent .musicBox1 audio').length; i < len; i++) {
                //如果是当前这个音频播放，那么就跳过，其它音频全部暂停
                if (thisIndex != i) {
                    $('.musicContent .musicBox1 audio')[i].pause();
                    $this.siblings('li').children('img').attr('src', 'img/playMusic.png');
                    $this.siblings('li').children('input').prop('checked', false);
                    $this.parent('ul').siblings('ul').children('li').children('img').attr('src', 'img/playMusic.png');
                    $this.parent('ul').siblings('ul').children('li').children('input').prop('checked', false);
                }
            }
        });
    },
    selectMusic2: function() {
        $('.musicContent>ul').eq(1).on('click', 'li', function() {
            var $this = $(this);
            var saveBtn = $('#warehouse .saveBtn');
            for (var j = 0; j < $('.musicContent .musicBox1 audio').length; j++) {
                $('.musicContent .musicBox1 audio')[j].pause();
            }
            //监听播放完毕 img回执
            $this.children('audio').get(0).addEventListener('ended', function() {
                $this.children('img').attr('src', 'img/playMusic.png');
                $this.children('input').prop('checked', false);
            }, false);
            if ($this.children('audio').get(0).paused) {
                $this.children('audio').get(0).play();
                $this.children('img').attr('src', 'img/stopMusic.png');
                $this.children('.musicCheck').prop('checked', true);
                saveBtn.addClass('btn-black');
            } else {
                $this.children('audio').get(0).pause();
                $this.children('img').attr('src', 'img/playMusic.png');
                $this.children('input').prop('checked', false);
                saveBtn.removeClass('btn-black');
            }
            var thisIndex = $this.index();
            for (var i = 0, len = $('.musicContent .musicBox2 audio').length; i < len; i++) {
                //如果是当前这个音频播放，那么就跳过，其它音频全部暂停
                if (thisIndex != i) {
                    $('.musicContent .musicBox2 audio')[i].pause();
                    $this.siblings('li').children('img').attr('src', 'img/playMusic.png');
                    $this.siblings('li').children('input').prop('checked', false);
                    $this.parent('ul').siblings('ul').children('li').children('img').attr('src', 'img/playMusic.png');
                    $this.parent('ul').siblings('ul').children('li').children('input').prop('checked', false);
                }
            }
        });
    },
    removerTopBgm: function() {
        $('#cloShowHide').click(function(e) {
            e.stopPropagation();
            $(this).addClass('hide');
            $(this).siblings('a').css('width', '120px').html('上传 / 挑选背景音乐');
            $('#selShowHide').addClass('hide');
            $('#new').removeClass('hide');
            orderFunc.updateHTML();
        })
    }
};
musicAle.init();

//文字滚动
var num = 0;
function goLeft() {
    if (num == -130) {
        num = 90;
    }
    num -= 1;
    $(".selecterP").css({
        left: num
    })
}
//设置滚动速度  pay.removeClass('mask_bor_bg'
var timer = setInterval(goLeft, 20);
//设置鼠标经过时滚动停止
$(".service_muscle_bg").hover(function() {
    clearInterval(timer);
}, function() {
    timer = setInterval(goLeft, 20);
});

$('#warehouse .saveBtn').click(function() {
    var $topBGM = $('.service_muscle_bg').eq(0);
    if ($(this).hasClass('btn-black')) {
        $('#selShowHide').removeClass('hide');
        $('#new').addClass('hide');
        $topBGM.css('width', '70px').html('<p class="selecterP">' + $('.musicCheck:checked').siblings('p').html() + '</p>');
        $warehouse.addClass('hide');
        $uploading.addClass('hide');
        $awb.addClass('hide');
        $('.btns>.custom>span').text('适合讲述');
        $(".music_upload_text").text('自定义背景音乐');
        musicAle.allStopMusic();
        $('.musicContent>ul>li>img').attr('src', 'img/playMusic.png');
        $('.musicContent>ul>li>input').prop('checked', false);
        $('.footer_rmb').html("￥ " + orderFunc.price + '<span>＞</span>'); // 更新价格
        // 背景音增价
        bgMusicPrice = 20
        $('#mask_money_origin').text("￥ " + Math.ceil(orderFunc.price / 0.7) + '.00' + " ");
        orderFunc.updateHTML();
        musicAle.cid = 0;
        musicAle.type = 0;
        $('#cloShowHide').removeClass('hide')
    }
});
// 上传背景音
$('#uploading .saveBtn').click(function() {
    var $topBGM = $('.service_muscle_bg').eq(0);
    bgMusicPrice = 20
    var musicPrice = orderFunc.price + bgMusicPrice;
    if ($(this).hasClass('btn-black')) {
        $('#selShowHide').removeClass('hide');
        $topBGM.css('width', '70px').html('<p class="selecterP"><span class="musicId hide">' + $('#saveUploadingFileId').text() + '</span><span class="musicType hide">2</span>' + $('#saveUploadingFileName').text() + '</p>');
        $warehouse.addClass('hide');
        $uploading.addClass('hide');
        $awb.addClass('hide');
        $('#new').addClass('hide');
        $('.btns>.custom>span').text('适合讲述');
        $(".music_upload_text").text('自定义背景音乐');
        $('.musicContent>ul>li>audio').get(0).pause();
        $('.musicContent>ul>li>img').attr('src', 'img/playMusic.png');
        $('.musicContent>ul>li>input').prop('checked', false);
        orderFunc.updateHTML();
        musicAle.cid = 0;
        musicAle.type = 0;
        $('#cloShowHide').removeClass('hide');
    }
});

for (var i = 0, len = $('audio').length; i < len; i++) {
    $('audio').get(i).addEventListener('ended', function() {
        $('.musicContent>ul>li>img').attr('src', 'img/playMusic.png')
    }, false);
}

function addMusic(kname, key) {
    $.post(apiCollect.apiPostMediaAdd, {
        name: kname,
        music: key
    }, function(data) {
        if (data.code == '000000') {
            $('#saveUploadingFileId').text(data.data);
            headtipObj2.show('背景音乐上传完成');
        } else {
            headtipObj.show(data.message);
            $uploading.addClass('hide');
            $awb.addClass('hide');
            $('#new').removeClass('hide');
            orderFunc.updateHTML();
        }
    })
}

function randomWord(randomFlag, min, max) {
    var str = "",
        range = min,
        arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

    // 随机产生
    if (randomFlag) {
        range = Math.round(Math.random() * (max - min)) + min;
    }
    for (var i = 0; i < range; i++) {
        pos = Math.round(Math.random() * (arr.length - 1));
        str += arr[pos];
    }
    return str;
}

var uploader = Qiniu.uploader({
    runtimes: 'html5,flash,html4', // 上传模式，依次退化
    browse_button: 'up_music', // 上传选择的点选按钮，必需
    uptoken_url: apiCollect.apiQiniuUpToken, // Ajax请求uptoken的Url，强烈建议设置（服务端提供）
    domain: "http://audio.heardtech.com", // bucket域名，下载资源时用到，必需
    container: 'container', // 上传区域DOM ID，默认是browser_button的父元素
    max_file_size: '30mb', // 最大文件体积限制
    max_retries: 3, // 上传失败最大重试次数
    dragdrop: true, // 开启可拖曳上传
    chunk_size: '30mb', // 分块上传时，每块的体积
    auto_start: true, // 选择文件后自动上传，若关闭需要自己绑定事件触发上传
    unique_names: false,
    save_key: false,
    filters: [
        { title: "Mp3 files", extensions: "mp3" }
    ],
    init: {
        'FilesAdded': function(up, files) {
            plupload.each(files, function(file) {
                // 文件添加进队列后，处理相关的事情
            });
        },
        'BeforeUpload': function(up, file) {
            // 每个文件上传前，处理相关的事情
            $('#pro-bar').show();
            $('#pro-bar').css('width', '0%')
        },
        'UploadProgress': function(up, file) {
            $('#up_music').hide();
            $('#pro-bar').css('width', file.percent + '%')
        },
        'FileUploaded': function(up, file, info) {
            $(".music_upload_text").html('上传完成');
            $('#uploading .saveBtn').addClass('btn-black');
            var key = $.parseJSON(info.response).key;
            var str = 'http://audio.heardtech.com/';
            var newKey = encodeURI(str + key);
            addMusic(file.name, newKey);
            $('#up_music').show();
            $('#pro-bar').hide()
        },
        'Error': function(up, err, errTip) {
            //上传出错时，处理相关的事情
        },
        'UploadComplete': function() {
            //队列文件处理完毕后，处理相关的事情
        },
        'Key': function(up, file) {
            var key = "";
            var keyName = file.name;
            $('#saveUploadingFileName').text(keyName);
            key = randomWord(true, 10, 100) + file.name;
            return key
        }
    }
});

function handlerIn() {
    $('#cost-tip').removeClass('hide')
}

function handlerOut() {
    $('#cost-tip').addClass('hide')
}
$('.payMoney').hover(handlerIn, handlerOut);

// 倒计时
var time_num = 60
function countDown(time,id){
    console.log(time_num)
    var counter = (function () {
        var count = time;
        time_num = 60
            return function () {
                time_num --
                if(time_num <= 20){
                    $('.select-anchor-btn').css({'background': "#FF260F",'opacity':'0.59'}).val('倒计时结束后，系统将帮你优选主播')
                }else{
                    $('.select-anchor-btn').css({'background': "#333",'opacity':'1'}).val('确认下单')
                }
                if(time_num < 1){
                    time_num = 0
                    clearInterval(timeCount)
                }
                $('#process-num').text(time_num+'s')
                return count-= 6
            }
    })();
    function begin () {
        $('#'+id).css('width',counter()+'px');
        if ($('#'+id).css('width') == time/6+'px') {

        }
    }
    var timeCount = setInterval(begin,1000);
}
$('#pay_back').click(function() {
    clearInterval(time3)
    $('.mask_pay_one').show().siblings().hide()
    $('#pay_back').hide()
    $('.order_head').eq(0).removeClass('colacacac').addClass('col585858');
     $('.order_head').eq(1).removeClass('col585858').addClass('colacacac');
});